[frontend] Improve api helper function

This commit is contained in:
Laura Hausmann 2023-12-15 17:14:46 +01:00
parent 80fbba219b
commit d7d2401ca0
No known key found for this signature in database
GPG key ID: D044E84C5BE01605
2 changed files with 9 additions and 4 deletions

View file

@ -5,7 +5,7 @@ import { onMounted, ref } from "vue";
const field = ref<HTMLElement>(); const field = ref<HTMLElement>();
onMounted(() => { onMounted(() => {
api('/api/iceshrimp/v1/auth').then(res => { api('/v1/auth').then(res => {
field.value!.textContent = JSON.stringify(res, null, 2); field.value!.textContent = JSON.stringify(res, null, 2);
}); });
}); });

View file

@ -1,15 +1,20 @@
import { get as kvGet } from "idb-keyval"; import { get as kvGet } from "idb-keyval";
import { KvAccount } from "../entities/keyval.ts"; 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 token = (await getCurrentAccount())?.token ?? null;
const headers: Record<string, string> = {};
if (token != null) headers['Authorization'] = `Bearer ${token}`;
if (body != null) headers['Content-Type'] = `application/json`;
const request = { const request = {
method: body ? 'POST' : 'GET', method: body ? 'POST' : 'GET',
headers: token ? { authorization: `Bearer ${token}` } : undefined, headers: headers,
body: body ? JSON.stringify(body) : undefined 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? //FIXME: cache this somewhere?