feat(admin): typed API client with session token handling

- Add api client for lists, members, held queue and archive
- Keep the bearer token in sessionStorage and clear it on 401
- Turn network and non-JSON errors into ApiError
This commit is contained in:
tgiachi 2026-11-09 15:30:13 +01:00
commit 97024ca642
2 changed files with 297 additions and 0 deletions

152
admin/src/lib/api.test.ts Normal file
View file

@ -0,0 +1,152 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { api, ApiError, session } from './api'
type Call = { url: string; init: RequestInit }
let calls: Call[]
function respond(status: number, body?: unknown) {
return () =>
Promise.resolve(
new Response(body === undefined ? null : JSON.stringify(body), {
status,
headers: body === undefined ? {} : { 'Content-Type': 'application/json' },
}),
)
}
function mockFetch(handler: (c: Call) => Promise<Response>) {
calls = []
vi.stubGlobal(
'fetch',
vi.fn((url: string, init: RequestInit = {}) => {
const c = { url, init }
calls.push(c)
return handler(c)
}),
)
}
beforeEach(() => session.set('secret-token'))
afterEach(() => {
vi.unstubAllGlobals()
session.onUnauthorized(null)
})
describe('session', () => {
it('keeps the token in sessionStorage only', () => {
session.set('abc')
expect(sessionStorage.getItem('parsimony.token')).toBe('abc')
expect(localStorage.getItem('parsimony.token')).toBeNull()
expect(session.get()).toBe('abc')
session.clear()
expect(session.get()).toBeNull()
})
})
describe('request', () => {
it('sends the bearer token and parses JSON', async () => {
mockFetch(respond(200, [{ id: 1 }]))
const lists = await api.lists.list()
expect(lists).toEqual([{ id: 1 }])
expect(calls[0].url).toBe('/api/v1/lists')
expect((calls[0].init.headers as Record<string, string>).Authorization).toBe('Bearer secret-token')
})
it('sends JSON bodies with a content type', async () => {
mockFetch(respond(201, { id: 2 }))
await api.lists.create({ name: 'dev', domain: 'example.org', title: 'Dev' })
expect(calls[0].init.method).toBe('POST')
expect(JSON.parse(calls[0].init.body as string)).toEqual({ name: 'dev', domain: 'example.org', title: 'Dev' })
expect((calls[0].init.headers as Record<string, string>)['Content-Type']).toBe('application/json')
})
it('returns undefined for 204', async () => {
mockFetch(respond(204))
await expect(api.lists.remove(3)).resolves.toBeUndefined()
expect(calls[0].init.method).toBe('DELETE')
expect(calls[0].url).toBe('/api/v1/lists/3')
})
it('throws ApiError with the server message', async () => {
mockFetch(respond(409, { error: 'already exists' }))
const err = await api.lists.create({ name: 'a', domain: 'b', title: 'c' }).catch((e) => e)
expect(err).toBeInstanceOf(ApiError)
expect(err.status).toBe(409)
expect(err.message).toBe('already exists')
})
it('falls back to a generic message when the body is not JSON', async () => {
mockFetch(() => Promise.resolve(new Response('<html>bad gateway</html>', { status: 502 })))
const err = await api.lists.list().catch((e) => e)
expect(err).toBeInstanceOf(ApiError)
expect(err.status).toBe(502)
expect(err.message).toMatch(/502/)
})
it('clears the token and notifies on 401', async () => {
const onUnauthorized = vi.fn()
session.onUnauthorized(onUnauthorized)
mockFetch(respond(401, { error: 'invalid or missing token' }))
await expect(api.lists.list()).rejects.toMatchObject({ status: 401 })
expect(session.get()).toBeNull()
expect(onUnauthorized).toHaveBeenCalledTimes(1)
})
it('turns network failures into ApiError', async () => {
mockFetch(() => Promise.reject(new TypeError('Failed to fetch')))
const err = await api.lists.list().catch((e) => e)
expect(err).toBeInstanceOf(ApiError)
expect(err.status).toBe(0)
expect(err.message).toMatch(/reach the server/i)
})
})
describe('endpoints', () => {
it('patches a list with only the given fields', async () => {
mockFetch(respond(200, { id: 1 }))
await api.lists.update(1, { post_policy: 'moderated' })
expect(calls[0].init.method).toBe('PATCH')
expect(JSON.parse(calls[0].init.body as string)).toEqual({ post_policy: 'moderated' })
})
it('encodes member addresses in the path', async () => {
mockFetch(respond(204))
await api.members.remove(1, 'a+b@example.com')
expect(calls[0].url).toBe('/api/v1/lists/1/members/a%2Bb%40example.com')
})
it('adds members', async () => {
mockFetch(respond(201, { address: 'a@x.com' }))
await api.members.add(7, { address: 'a@x.com', display_name: 'A' })
expect(calls[0].url).toBe('/api/v1/lists/7/members')
expect(JSON.parse(calls[0].init.body as string)).toEqual({ address: 'a@x.com', display_name: 'A' })
})
it('approves and discards held messages', async () => {
mockFetch(respond(204))
await api.held.approve(5)
await api.held.discard(5)
expect(calls.map((c) => [c.init.method, c.url])).toEqual([
['POST', '/api/v1/held/5/approve'],
['DELETE', '/api/v1/held/5'],
])
})
it('builds the archive query string and skips empty values', async () => {
mockFetch(respond(200, { total: 0, messages: [] }))
await api.archive.list(2, { q: 'deploy & go', limit: 25, offset: 50 })
await api.archive.list(2, { q: '', limit: 25, offset: 0 })
expect(calls[0].url).toBe('/api/v1/lists/2/archive?q=deploy+%26+go&limit=25&offset=50')
expect(calls[1].url).toBe('/api/v1/lists/2/archive?limit=25&offset=0')
})
it('reads and deletes archived messages', async () => {
mockFetch(respond(204))
await api.archive.remove(9)
await api.archive.get(9).catch(() => undefined)
expect(calls.map((c) => [c.init.method, c.url])).toEqual([
['DELETE', '/api/v1/archive/9'],
['GET', '/api/v1/archive/9'],
])
})
})

145
admin/src/lib/api.ts Normal file
View file

@ -0,0 +1,145 @@
// Typed client for the Parsimony admin REST API (/api/v1).
export type PostPolicy = 'members' | 'moderated'
export type JoinPolicy = 'open' | 'closed'
export type ArchivePolicy = 'public' | 'private' | 'off'
export interface List {
id: number
name: string
domain: string
title: string
address: string
post_policy: PostPolicy
join_policy: JoinPolicy
archive_policy: ArchivePolicy
}
export interface Member {
address: string
display_name: string
disabled: boolean
bounce_count: number
}
export interface Held {
id: number
sender: string
subject: string
size: number
created_at: string
}
export interface Message {
id: number
thread_id: number
message_id: string
in_reply_to?: string
subject: string
sender: string
date: string
size: number
body?: string
}
export interface ArchivePage {
total: number
messages: Message[]
}
export class ApiError extends Error {
readonly status: number
constructor(status: number, message: string) {
super(message)
this.name = 'ApiError'
this.status = status
}
}
const TOKEN_KEY = 'parsimony.token'
let unauthorizedHandler: (() => void) | null = null
/** The bearer token lives in sessionStorage: it dies with the tab. */
export const session = {
get: (): string | null => sessionStorage.getItem(TOKEN_KEY),
set: (token: string) => sessionStorage.setItem(TOKEN_KEY, token),
clear: () => sessionStorage.removeItem(TOKEN_KEY),
/** Called after any 401, once the token has been cleared. */
onUnauthorized: (fn: (() => void) | null) => {
unauthorizedHandler = fn
},
}
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
const headers: Record<string, string> = {}
const token = session.get()
if (token) headers.Authorization = `Bearer ${token}`
if (body !== undefined) headers['Content-Type'] = 'application/json'
let res: Response
try {
res = await fetch(`/api/v1${path}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
})
} catch {
throw new ApiError(0, 'Cannot reach the server')
}
if (res.status === 401) {
session.clear()
unauthorizedHandler?.()
}
if (!res.ok) {
let message = `Request failed (${res.status})`
try {
const data = await res.json()
if (typeof data?.error === 'string') message = data.error
} catch {
// not JSON: keep the generic message
}
throw new ApiError(res.status, message)
}
if (res.status === 204) return undefined as T
return (await res.json()) as T
}
const enc = encodeURIComponent
export const api = {
lists: {
list: () => request<List[]>('GET', '/lists'),
get: (id: number) => request<List>('GET', `/lists/${id}`),
create: (b: { name: string; domain: string; title?: string }) => request<List>('POST', '/lists', b),
update: (
id: number,
b: Partial<Pick<List, 'title' | 'post_policy' | 'join_policy' | 'archive_policy'>>,
) => request<List>('PATCH', `/lists/${id}`, b),
remove: (id: number) => request<void>('DELETE', `/lists/${id}`),
},
members: {
list: (listId: number) => request<Member[]>('GET', `/lists/${listId}/members`),
add: (listId: number, b: { address: string; display_name?: string }) =>
request<Member>('POST', `/lists/${listId}/members`, b),
remove: (listId: number, address: string) =>
request<void>('DELETE', `/lists/${listId}/members/${enc(address)}`),
},
held: {
list: (listId: number) => request<Held[]>('GET', `/lists/${listId}/held`),
approve: (id: number) => request<void>('POST', `/held/${id}/approve`),
discard: (id: number) => request<void>('DELETE', `/held/${id}`),
},
archive: {
list: (listId: number, p: { q?: string; limit?: number; offset?: number } = {}) => {
const qs = new URLSearchParams()
if (p.q) qs.set('q', p.q)
if (p.limit !== undefined) qs.set('limit', String(p.limit))
if (p.offset !== undefined) qs.set('offset', String(p.offset))
const s = qs.toString()
return request<ArchivePage>('GET', `/lists/${listId}/archive${s ? `?${s}` : ''}`)
},
get: (id: number) => request<Message>('GET', `/archive/${id}`),
remove: (id: number) => request<void>('DELETE', `/archive/${id}`),
},
}