feat: REST API client module
This commit is contained in:
parent
ac681dbfaa
commit
a13f2b821b
1 changed files with 70 additions and 0 deletions
70
src/sync/api.ts
Normal file
70
src/sync/api.ts
Normal file
|
|
@ -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<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)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue