client: refactor API calling

This commit is contained in:
Johann150 2024-02-22 22:26:32 +01:00
parent d4a5ed29db
commit dbdb2b70f1
Signed by untrusted user: Johann150
GPG key ID: 9EE6577A2A06F8F1
2 changed files with 6 additions and 8 deletions

View file

@ -27,7 +27,7 @@ export const api = ((endpoint: string, data: Record<string, any> = {}, token?: s
const authorization = authorizationToken ? `Bearer ${authorizationToken}` : undefined;
const promise = new Promise<void>((resolve, reject) => {
fetch(endpoint.indexOf('://') > -1 ? endpoint : `${apiUrl}/${endpoint}`, {
fetch(`${apiUrl}/${endpoint}`, {
method: 'POST',
body: JSON.stringify(data),
credentials: 'omit',
@ -37,13 +37,12 @@ export const api = ((endpoint: string, data: Record<string, any> = {}, token?: s
...(authorization ? { authorization } : {}),
},
}).then(async (res) => {
const body = res.status === 204 ? null : await res.json();
if (res.status === 200) {
resolve(body);
resolve(await res.json());
} else if (res.status === 204) {
resolve();
} else {
const body = await res.json();
reject(body.error);
}
}).catch(reject);
@ -77,13 +76,12 @@ export const apiGet = ((endpoint: string, data: Record<string, any> = {}, token?
...(authorization ? { authorization } : {}),
},
}).then(async (res) => {
const body = res.status === 204 ? null : await res.json();
if (res.status === 200) {
resolve(body);
resolve(await res.json());
} else if (res.status === 204) {
resolve();
} else {
const body = await res.json();
reject(body.error);
}
}).catch(reject);

View file

@ -23,7 +23,7 @@ export async function initializeSw() {
function encode(buffer: ArrayBuffer | null) {
return btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)));
}
// Register
api('sw/register', {
endpoint: subscription.endpoint,