feat [front]: cleanup api helper

This commit is contained in:
Alice 2022-12-26 00:11:56 +01:00
parent 82ffcb17d6
commit 8aa9854fa9

View file

@ -1,6 +1,6 @@
import { useLoadingStore } from "~/stores/loadingStore"
type MyHeaders = { [key: string]: string }
type MyHeaders = Record<string, string>
const makeLoadingKey = (path: string) => {
// camel-case the path : auth/login -> authLogin
@ -19,7 +19,7 @@ const makeLoadingKey = (path: string) => {
}
const getCsrfCookie = () => {
let cookie: string
let cookie: string | undefined
if (process.server) {
cookie = useRequestHeaders(["cookie"])["cookie"]
} else {
@ -36,6 +36,7 @@ const getCsrfCookie = () => {
}
const getHeaders = (includeCsrf = false): MyHeaders => {
// @ts-expect-error TODO handle null values here
const headers: MyHeaders = useRequestHeaders(["cookie"])
if (includeCsrf) {
const csfrToken = getCsrfCookie()
@ -64,30 +65,24 @@ const baseUrl = `${host}/api/`
export async function apiRequest<Type>(
method: string,
path: string,
payload,
payload: Record<never, never> | undefined,
params = {}
) {
const loadingStore = useLoadingStore()
const key = makeLoadingKey(path)
loadingStore.markLoading(key)
const response = await useAsyncData<Type>(
key,
() =>
$fetch(baseUrl + path, {
method: method,
body: payload,
credentials: "include",
headers: getHeaders(method != "GET"),
params: params,
}),
{ initialCache: false }
const response = await useAsyncData<Type>(key, () =>
$fetch<Type>(baseUrl + path, {
method: method,
body: payload,
credentials: "include",
headers: getHeaders(method != "GET"),
params: params,
})
)
if (response.error.value) {
loadingStore.markError(key)
} else {
loadingStore.markDone(key)
}
if (response.error.value) loadingStore.markError(key)
else loadingStore.markDone(key)
return response
}