feat(web): lists in query values, request cancelling and Retry-After in the API client
A list value is sent once per item (seed=1&seed=2). A signal can cancel a request and a cancelled call rejects with AbortError, not as a lost connection. ApiError keeps Retry-After in seconds.
This commit is contained in:
parent
64c14a51c5
commit
54b19d6d4f
2 changed files with 72 additions and 8 deletions
|
|
@ -111,3 +111,47 @@ test('a network failure becomes an ApiError with the code network', async () =>
|
|||
)
|
||||
await expect(api.get('/artists')).rejects.toMatchObject({ status: 0, code: 'network' })
|
||||
})
|
||||
|
||||
test('a list value is sent once for each item', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/discover': () => ({}) })
|
||||
await api.get('/discover', { seed: [3, 5], limit: 10 })
|
||||
expect(calls[0].url.searchParams.getAll('seed')).toEqual(['3', '5'])
|
||||
expect(calls[0].url.searchParams.get('limit')).toBe('10')
|
||||
})
|
||||
|
||||
test('a signal is given to the request', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/discover': () => ({}) })
|
||||
const controller = new AbortController()
|
||||
await api.get('/discover', undefined, { signal: controller.signal })
|
||||
expect(calls[0].init.signal).toBe(controller.signal)
|
||||
})
|
||||
|
||||
test('a cancelled request is not reported as a network failure', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => {
|
||||
throw new DOMException('aborted', 'AbortError')
|
||||
}),
|
||||
)
|
||||
const failure = await api.get('/discover').catch((e: unknown) => e)
|
||||
expect(failure).not.toBeInstanceOf(ApiError)
|
||||
expect(failure).toMatchObject({ name: 'AbortError' })
|
||||
})
|
||||
|
||||
test('Retry-After on an error is kept in seconds', async () => {
|
||||
mockFetch({
|
||||
'GET /api/v1/discover': () =>
|
||||
new Response(JSON.stringify({ error: { code: 'discover_busy', message: 'busy' } }), {
|
||||
status: 429,
|
||||
headers: { 'Content-Type': 'application/json', 'Retry-After': '12' },
|
||||
}),
|
||||
})
|
||||
const failure = await api.get('/discover').catch((e: unknown) => e)
|
||||
expect(failure).toMatchObject({ status: 429, code: 'discover_busy', retryAfter: 12 })
|
||||
})
|
||||
|
||||
test('an error without Retry-After has none', async () => {
|
||||
mockFetch({ 'GET /api/v1/artists': () => apiError(400, 'invalid_input') })
|
||||
const failure = (await api.get('/artists').catch((e: unknown) => e)) as ApiError
|
||||
expect(failure.retryAfter).toBeUndefined()
|
||||
})
|
||||
|
|
|
|||
|
|
@ -2,12 +2,15 @@
|
|||
export class ApiError extends Error {
|
||||
status: number
|
||||
code: string
|
||||
/** Seconds to wait before asking again, when the server said so (`Retry-After`). */
|
||||
retryAfter?: number
|
||||
|
||||
constructor(status: number, code: string, message: string) {
|
||||
constructor(status: number, code: string, message: string, retryAfter?: number) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
this.status = status
|
||||
this.code = code
|
||||
this.retryAfter = retryAfter
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -29,13 +32,17 @@ export function setAuthHooks(next: AuthHooks): void {
|
|||
hooks = next
|
||||
}
|
||||
|
||||
type Query = Record<string, string | number | boolean | undefined>
|
||||
type QueryValue = string | number | boolean | undefined
|
||||
/** A list value is sent once for each item (`seed=1&seed=2`). */
|
||||
type Query = Record<string, QueryValue | QueryValue[]>
|
||||
|
||||
export interface CallOptions {
|
||||
/** Default true. Login, register, refresh and logout say false: they carry no token and never renew. */
|
||||
auth?: boolean
|
||||
/** Lets the request finish after the page is closed (the browser allows it for small bodies). */
|
||||
keepalive?: boolean
|
||||
/** Cancels the request. A cancelled call rejects with the browser's `AbortError`, not an `ApiError`. */
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
const BASE = '/api/v1'
|
||||
|
|
@ -43,7 +50,9 @@ const BASE = '/api/v1'
|
|||
function buildUrl(path: string, params?: Query): string {
|
||||
const query = new URLSearchParams()
|
||||
for (const [key, value] of Object.entries(params ?? {})) {
|
||||
if (value !== undefined) query.set(key, String(value))
|
||||
for (const item of Array.isArray(value) ? value : [value]) {
|
||||
if (item !== undefined) query.append(key, String(item))
|
||||
}
|
||||
}
|
||||
const text = query.toString()
|
||||
return `${BASE}${path}${text ? `?${text}` : ''}`
|
||||
|
|
@ -52,18 +61,26 @@ function buildUrl(path: string, params?: Query): string {
|
|||
async function toApiError(res: Response): Promise<ApiError> {
|
||||
try {
|
||||
const body = (await res.json()) as { error?: { code?: string; message?: string } }
|
||||
return new ApiError(res.status, body.error?.code ?? 'unknown', body.error?.message ?? res.statusText)
|
||||
return new ApiError(res.status, body.error?.code ?? 'unknown', body.error?.message ?? res.statusText, retryAfter(res))
|
||||
} catch {
|
||||
return new ApiError(res.status, 'unknown', res.statusText)
|
||||
return new ApiError(res.status, 'unknown', res.statusText, retryAfter(res))
|
||||
}
|
||||
}
|
||||
|
||||
/** The `Retry-After` header in whole seconds, or nothing when it is absent or is a date. */
|
||||
function retryAfter(res: Response): number | undefined {
|
||||
const text = res.headers.get('Retry-After')
|
||||
if (text === null || !/^\d+$/.test(text.trim())) return undefined
|
||||
return Number(text)
|
||||
}
|
||||
|
||||
async function send(
|
||||
method: string,
|
||||
url: string,
|
||||
body: unknown,
|
||||
token: string | null,
|
||||
keepalive: boolean | undefined,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<Response> {
|
||||
const headers: Record<string, string> = { Accept: 'application/json' }
|
||||
if (body !== undefined) headers['Content-Type'] = 'application/json'
|
||||
|
|
@ -74,8 +91,11 @@ async function send(
|
|||
headers,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
keepalive: keepalive || undefined,
|
||||
signal,
|
||||
})
|
||||
} catch {
|
||||
} catch (e) {
|
||||
// A cancelled request is the caller's own doing: say so as it is, not as a broken connection.
|
||||
if (e instanceof DOMException && e.name === 'AbortError') throw e
|
||||
throw new ApiError(0, 'network', 'The server cannot be reached')
|
||||
}
|
||||
}
|
||||
|
|
@ -83,11 +103,11 @@ async function send(
|
|||
async function request<T>(method: string, path: string, params: Query | undefined, body: unknown, opts: CallOptions): Promise<T> {
|
||||
const auth = opts.auth ?? true
|
||||
const url = buildUrl(path, params)
|
||||
let res = await send(method, url, body, auth ? await hooks.getAccessToken() : null, opts.keepalive)
|
||||
let res = await send(method, url, body, auth ? await hooks.getAccessToken() : null, opts.keepalive, opts.signal)
|
||||
|
||||
if (res.status === 401 && auth) {
|
||||
const fresh = await hooks.refresh()
|
||||
if (fresh) res = await send(method, url, body, fresh, opts.keepalive)
|
||||
if (fresh) res = await send(method, url, body, fresh, opts.keepalive, opts.signal)
|
||||
if (res.status === 401) hooks.signOut()
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue