cineclub-site/front/composables/api.ts

105 lines
2.5 KiB
TypeScript
Raw Normal View History

2022-04-09 00:40:19 +02:00
import { useLoadingStore } from "~/stores/loadingStore"
type MyHeaders = { [key: string]: string }
const makeLoadingKey = (path: string) => {
// camel-case the path : auth/login -> authLogin
if (path.endsWith("/")) {
path = path.slice(0, -1)
}
if (path.startsWith("/")) {
path = path.slice(1)
}
let words = path.split("/")
words = words.filter((word) => !/^\d+$/.test(word))
for (const [ix, word] of Object.entries(words.slice(1))) {
words[parseInt(ix) + 1] = word[0].toUpperCase() + word.slice(1)
}
return words.join("")
}
2022-07-18 22:24:28 +02:00
const getCsrfCookie = () => {
let cookie: string
if (process.server) {
cookie = useRequestHeaders(["cookie"])["cookie"]
} else {
2022-04-09 00:40:19 +02:00
cookie = document.cookie
}
if (!cookie) {
return null
}
2022-07-18 22:24:28 +02:00
const csrfRow = cookie.split("; ").find((row) => row.startsWith("csrftoken="))
if (!csrfRow) {
2022-04-09 00:40:19 +02:00
return null
}
2022-07-18 22:24:28 +02:00
return csrfRow.split("=")[1]
2022-04-09 00:40:19 +02:00
}
2022-07-18 22:24:28 +02:00
const getHeaders = (includeCsrf = false): MyHeaders => {
2022-04-09 00:40:19 +02:00
const headers: MyHeaders = useRequestHeaders(["cookie"])
if (includeCsrf) {
2022-07-18 22:24:28 +02:00
const csfrToken = getCsrfCookie()
2022-04-09 00:40:19 +02:00
if (csfrToken) {
headers["X-CSRFTOKEN"] = csfrToken
}
}
return headers
}
let host
// local
if (process.env.NODE_ENV !== "production") {
host = "http://localhost:8000"
} else {
// production server
if (process.server) {
// server-side rendering
host = "http://localhost:8064"
} else {
host = "https://cineclub.ens.fr" //use env params ?
}
}
const baseUrl = `${host}/api/`
export async function apiRequest<Type>(
method: string,
path: string,
payload,
params = {}
) {
const loadingStore = useLoadingStore()
const key = makeLoadingKey(path)
loadingStore.markLoading(key)
2022-07-18 22:24:28 +02:00
const response = await useAsyncData<Type>(
key,
() =>
$fetch(baseUrl + path, {
method: method,
body: payload,
credentials: "include",
headers: getHeaders(method != "GET"),
params: params,
}),
{ initialCache: false }
2022-04-09 00:40:19 +02:00
)
2022-07-18 22:24:28 +02:00
if (response.error.value) {
2022-04-09 00:40:19 +02:00
loadingStore.markError(key)
} else {
loadingStore.markDone(key)
}
2022-07-18 22:24:28 +02:00
return response
2022-04-09 00:40:19 +02:00
}
export async function apiGet<Type>(path: string, params = {}) {
return apiRequest<Type>("GET", path, undefined, params)
}
export async function apiPost<Type>(path: string, payload = {}, params = {}) {
return apiRequest<Type>("POST", path, payload, params)
}
export async function apiPatch<Type>(path: string, payload = {}, params = {}) {
return apiRequest<Type>("PATCH", path, payload, params)
}