From d7d2401ca0715a5099b99633301a6615db0b56f1 Mon Sep 17 00:00:00 2001 From: Laura Hausmann Date: Fri, 15 Dec 2023 17:14:46 +0100 Subject: [PATCH] [frontend] Improve api helper function --- packages/frontend/src/components/AuthDebug.vue | 2 +- packages/frontend/src/helpers/api.ts | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/frontend/src/components/AuthDebug.vue b/packages/frontend/src/components/AuthDebug.vue index 2fc65498d..87665a217 100644 --- a/packages/frontend/src/components/AuthDebug.vue +++ b/packages/frontend/src/components/AuthDebug.vue @@ -5,7 +5,7 @@ import { onMounted, ref } from "vue"; const field = ref(); onMounted(() => { - api('/api/iceshrimp/v1/auth').then(res => { + api('/v1/auth').then(res => { field.value!.textContent = JSON.stringify(res, null, 2); }); }); diff --git a/packages/frontend/src/helpers/api.ts b/packages/frontend/src/helpers/api.ts index a30b8fae2..ed1c91c27 100644 --- a/packages/frontend/src/helpers/api.ts +++ b/packages/frontend/src/helpers/api.ts @@ -1,15 +1,20 @@ import { get as kvGet } from "idb-keyval"; import { KvAccount } from "../entities/keyval.ts"; -export async function api(endpoint: string, body?: object) { +export async function api(endpoint: string, body?: object, prefix: string = '/api/iceshrimp') { const token = (await getCurrentAccount())?.token ?? null; + const headers: Record = {}; + + if (token != null) headers['Authorization'] = `Bearer ${token}`; + if (body != null) headers['Content-Type'] = `application/json`; + const request = { method: body ? 'POST' : 'GET', - headers: token ? { authorization: `Bearer ${token}` } : undefined, + headers: headers, body: body ? JSON.stringify(body) : undefined }; - return fetch(endpoint, request).then(res => res.json()); + return fetch(prefix + endpoint, request).then(res => res.json()); } //FIXME: cache this somewhere?