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