Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 61 additions & 3 deletions apps/web/src/lib/__test__/api-client.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { api } from '@/lib/api-client';
import { serve } from '@/testing/respond';
import { failToConnect, serve } from '@/testing/respond';
import {
DeviceTokenStorageError,
getToken,
Expand Down Expand Up @@ -66,14 +66,72 @@ describe('api client', () => {
);
});

it('reports the message of any other failure', async () => {
it('reports the literal the API sends as plain text', async () => {
serve(404, 'Line item not found');

await api.sessions({ sessionId: SESSION_ID }).get();

expect(toastAdd).toHaveBeenCalledWith(
expect.objectContaining({ description: 'Line item not found' }),
);
});

it('reports a proxy error page as it comes', async () => {
const page = '<html><body>Bad Gateway</body></html>';
serve(502, page);

await api.sessions({ sessionId: SESSION_ID }).get();

expect(toastAdd).toHaveBeenCalledWith(
expect.objectContaining({ description: page }),
);
});

it('reports a validation failure as it comes', async () => {
const body = {
type: 'validation',
on: 'body',
property: '/image',
message: 'Expected required property',
};
serve(422, body);

await api.sessions({ sessionId: SESSION_ID }).get();

expect(toastAdd).toHaveBeenCalledWith(
expect.objectContaining({ description: JSON.stringify(body) }),
);
});

it('reports a failure to reach the server', async () => {
failToConnect();

const { error } = await api.sessions({ sessionId: SESSION_ID }).get();

expect(error?.status).toBe(503);
expect(toastAdd).toHaveBeenCalledWith(
expect.objectContaining({
description: "We couldn't reach the server. Check your connection.",
}),
);
});

it('says nothing when the request was aborted', async () => {
failToConnect(new DOMException('Aborted', 'AbortError'));

await api.sessions({ sessionId: SESSION_ID }).get();

expect(toastAdd).not.toHaveBeenCalled();
});

it('reports the body of any other failure', async () => {
serve(500, { message: 'Something broke' });

await api.sessions({ sessionId: SESSION_ID }).get();

expect(getToken(SESSION_ID)).toEqual(auth);
expect(toastAdd).toHaveBeenCalledWith(
expect.objectContaining({ description: 'Something broke' }),
expect.objectContaining({ description: '{"message":"Something broke"}' }),
);
});

Expand Down
31 changes: 18 additions & 13 deletions apps/web/src/lib/api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,44 @@ import { env } from '@/config/env';
import { DeviceTokenStorageError } from '@/utils/device-token';
import { authHeader, expireSession, persistAuth } from './auth';

const NETWORK_ERROR = "We couldn't reach the server. Check your connection.";

export const api: Treaty.Create<App> = treaty<App>(env.apiUrl, {
fetcher,
headers: (path) => authHeader(path),
async onResponse(response) {
if (response.ok) {
if (await persistAuth(response)) return;

const error = new DeviceTokenStorageError();
toast.add({ type: 'error', title: 'Error', description: error.message });
report(error.message);
throw error;
}

if (response.status === 401 && expireSession(response.url)) return;

toast.add({
type: 'error',
title: 'Error',
description: await errorMessage(response),
});
report(await response.clone().text());
Comment thread
aek676 marked this conversation as resolved.
Resolved
},
});

async function errorMessage(response: Response): Promise<string> {
async function fetcher(
Comment thread
aek676 marked this conversation as resolved.
Resolved
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> {
try {
const body = await response.clone().json();
return await fetch(input, init);
} catch (error) {
if (!(error instanceof DOMException && error.name === 'AbortError'))
report(NETWORK_ERROR);

return typeof body === 'string'
? body
: (body?.message ?? body?.value?.message ?? response.statusText);
} catch {
return response.statusText;
throw error;
}
}

function report(description: string): void {
toast.add({ type: 'error', title: 'Error', description });
}

export function apiError(error: unknown, message: string): Error {
return new Error(message, { cause: error });
}
30 changes: 26 additions & 4 deletions apps/web/src/testing/respond.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
import { vi } from 'vitest';

/**
* Mirrors what Elysia puts on the wire: objects are JSON, string literals go out
* raw as `text/plain`, and `statusText` stays empty the way it does over HTTP/2.
*/
export function respond(url: string, status: number, body: unknown): Response {
const isJson = typeof body === 'object' && body !== null;

const make = (): Response => {
const response = new Response(JSON.stringify(body), {
status,
headers: { 'content-type': 'application/json' },
});
const response = new Response(
body === undefined ? null : isJson ? JSON.stringify(body) : String(body),
{
status,
headers: {
'content-type': isJson
? 'application/json'
: 'text/plain;charset=utf-8',
},
},
);
Object.defineProperty(response, 'url', { value: url });
Object.defineProperty(response, 'clone', { value: make });

Expand All @@ -21,3 +34,12 @@ export function serve(status: number, body: unknown) {
vi.fn(async (url: string) => respond(url, status, body)),
);
}

export function failToConnect(error: Error = new TypeError('Failed to fetch')) {
vi.stubGlobal(
'fetch',
vi.fn(async () => {
throw error;
}),
);
}