import { type Role, roleOf } from './AuthStore'; import { apiRequest, jsonBody } from './http'; import type { Account, AccountChange, UsersStore } from './UsersStore'; /** A refusal of the API (4xx with an `{error}`) as its bare sentence, without route and status around it. */ function refusal(status: number, data: unknown): Error | undefined { const message = (data as { error?: unknown } | null)?.error; return status >= 400 && status < 500 && typeof message === 'string' ? new Error(message) : undefined; } export class HttpUsersStore implements UsersStore { constructor(private readonly endpoint: string) {} async list(): Promise { const rows = await apiRequest(this.endpoint, 'GET', 'users', {}, refusal); return rows.map((row) => ({ ...row, role: roleOf(row.role) })); } async create(username: string, password: string, role: Role): Promise { await apiRequest(this.endpoint, 'POST', 'users', jsonBody({ username, password, role }), refusal); } async update(username: string, change: AccountChange): Promise { await apiRequest(this.endpoint, 'PATCH', `users/${username}`, jsonBody(change), refusal); } async remove(username: string): Promise { await apiRequest(this.endpoint, 'DELETE', `users/${username}`, {}, refusal); } }