From a13f2b821b95f714d524ba5413a121d6abea771c Mon Sep 17 00:00:00 2001 From: eddy Date: Mon, 20 Jul 2026 16:55:50 +0200 Subject: [PATCH] feat: REST API client module --- src/sync/api.ts | 70 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/sync/api.ts diff --git a/src/sync/api.ts b/src/sync/api.ts new file mode 100644 index 0000000..143ec7b --- /dev/null +++ b/src/sync/api.ts @@ -0,0 +1,70 @@ +import { Measurement } from '../types' +import { ApiConfig } from '../types' + +export class ApiError extends Error { + status: number + constructor(message: string, status: number) { + super(message) + this.name = 'ApiError' + this.status = status + } +} + +function authHeaders(token: string): Record { + return { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + } +} + +export type Api = ReturnType + +export function createApi(config: ApiConfig) { + const base = config.url.replace(/\/+$/, '') + + return { + async getMeasurements(since?: string): Promise { + let url = `${base}/api/v1/measurements` + if (since) { + url += `?since=${encodeURIComponent(since)}` + } + const response = await fetch(url, { + headers: { Authorization: `Bearer ${config.token}` }, + }) + if (response.status === 401) { + throw new ApiError('Authenticatie mislukt. Controleer je token in Instellingen.', 401) + } + if (!response.ok) { + throw new ApiError(`Serverfout bij ophalen metingen: ${response.status}`, response.status) + } + return response.json() + }, + + async createMeasurement(m: Measurement): Promise { + const response = await fetch(`${base}/api/v1/measurements`, { + method: 'POST', + headers: authHeaders(config.token), + body: JSON.stringify(m), + }) + if (response.status === 401) { + throw new ApiError('Authenticatie mislukt. Controleer je token in Instellingen.', 401) + } + if (!response.ok) { + throw new ApiError(`Serverfout bij opslaan meting: ${response.status}`, response.status) + } + }, + + async deleteMeasurement(id: string): Promise { + const response = await fetch(`${base}/api/v1/measurements/${id}`, { + method: 'DELETE', + headers: { Authorization: `Bearer ${config.token}` }, + }) + if (response.status === 401) { + throw new ApiError('Authenticatie mislukt. Controleer je token in Instellingen.', 401) + } + if (!response.ok) { + throw new ApiError(`Serverfout bij verwijderen meting: ${response.status}`, response.status) + } + }, + } +}