2022-01-20 19:42:30 +01:00
|
|
|
import {
|
|
|
|
createAPIClient,
|
|
|
|
CookieUtils,
|
|
|
|
Constants,
|
|
|
|
} from "@budibase/frontend-core"
|
2022-01-24 17:38:36 +01:00
|
|
|
import { store } from "./builderStore"
|
2022-01-20 19:42:30 +01:00
|
|
|
import { get } from "svelte/store"
|
2023-04-25 09:44:57 +02:00
|
|
|
import { auth } from "./stores/portal"
|
2020-11-03 14:45:49 +01:00
|
|
|
|
2022-01-20 19:42:30 +01:00
|
|
|
export const API = createAPIClient({
|
|
|
|
attachHeaders: headers => {
|
|
|
|
// Attach app ID header from store
|
2023-04-25 09:44:57 +02:00
|
|
|
let appId = get(store).appId
|
2023-04-25 09:35:25 +02:00
|
|
|
if (appId) {
|
|
|
|
headers["x-budibase-app-id"] = appId
|
2023-04-24 21:39:39 +02:00
|
|
|
}
|
2022-01-31 10:40:33 +01:00
|
|
|
|
|
|
|
// Add csrf token if authenticated
|
|
|
|
const user = get(auth).user
|
|
|
|
if (user?.csrfToken) {
|
|
|
|
headers["x-csrf-token"] = user.csrfToken
|
|
|
|
}
|
2022-01-20 19:42:30 +01:00
|
|
|
},
|
|
|
|
|
|
|
|
onError: error => {
|
2022-01-21 10:10:59 +01:00
|
|
|
const { url, message, status, method, handled } = error || {}
|
2022-01-20 19:42:30 +01:00
|
|
|
|
2022-01-21 10:10:59 +01:00
|
|
|
// Log any errors that we haven't manually handled
|
|
|
|
if (!handled) {
|
|
|
|
console.error("Unhandled error from API client", error)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Log all errors to console
|
2022-01-24 17:40:55 +01:00
|
|
|
console.warn(`[Builder] HTTP ${status} on ${method}:${url}\n\t${message}`)
|
2022-01-21 10:10:59 +01:00
|
|
|
|
2022-01-20 19:42:30 +01:00
|
|
|
// Logout on 403's
|
|
|
|
if (status === 403) {
|
2022-01-25 16:28:31 +01:00
|
|
|
// Remove cookies
|
2022-01-20 12:19:37 +01:00
|
|
|
CookieUtils.removeCookie(Constants.Cookies.Auth)
|
2022-01-20 19:42:30 +01:00
|
|
|
|
|
|
|
// Reload after removing cookie, go to login
|
2021-10-15 18:52:06 +02:00
|
|
|
if (!url.includes("self") && !url.includes("login")) {
|
2021-06-22 17:54:25 +02:00
|
|
|
location.reload()
|
|
|
|
}
|
2021-06-15 20:39:40 +02:00
|
|
|
}
|
2022-01-20 19:42:30 +01:00
|
|
|
},
|
|
|
|
})
|