cineclub-site/front/composables/api.ts

102 lines
2.5 KiB
TypeScript

import { NuxtApp } from "nuxt3/dist/app/nuxt"
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("")
}
const getCsrfCookie = (ctx: NuxtApp) => {
let cookie = ""
if (ctx?.ssrContext?.req.headers.cookie) {
cookie = ctx?.ssrContext.req.headers.cookie
} else if (process.client) {
cookie = document.cookie
}
if (!cookie) {
return null
}
const csfrRow = cookie.split("; ").find((row) => row.startsWith("csrftoken="))
if (!csfrRow) {
return null
}
return csfrRow.split("=")[1]
}
const getHeaders = (ctx: NuxtApp, includeCsrf = false): MyHeaders => {
const headers: MyHeaders = useRequestHeaders(["cookie"])
if (includeCsrf) {
const csfrToken = getCsrfCookie(ctx)
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)
const { data, error } = await useAsyncData<Type>(key, (ctx) =>
$fetch(baseUrl + path, {
method: method,
body: payload,
credentials: "include",
headers: getHeaders(ctx, true),
params: params,
})
)
if (error.value) {
loadingStore.markError(key)
} else {
loadingStore.markDone(key)
}
return { data, error }
}
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)
}