70 lines
2.2 KiB
TypeScript
70 lines
2.2 KiB
TypeScript
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<string, string> {
|
|
return {
|
|
Authorization: `Bearer ${token}`,
|
|
'Content-Type': 'application/json',
|
|
}
|
|
}
|
|
|
|
export type Api = ReturnType<typeof createApi>
|
|
|
|
export function createApi(config: ApiConfig) {
|
|
const base = config.url.replace(/\/+$/, '')
|
|
|
|
return {
|
|
async getMeasurements(since?: string): Promise<Measurement[]> {
|
|
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<void> {
|
|
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<void> {
|
|
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)
|
|
}
|
|
},
|
|
}
|
|
}
|