Skip to content
Open
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
27 changes: 27 additions & 0 deletions __tests__/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,30 @@ describe("post", () => {
await expect(post("/api/test", {})).rejects.toThrow("Bad request");
});
});

for (const [method, send] of [
["GET", () => get("/api/test")],
["POST", () => post("/api/test", {})],
] as const) {
describe(`${method} response contract`, () => {
it.each([
[false, { error: "Preferred", message: "Other" }, "Preferred"],
[false, { message: "Rejected" }, "Rejected"],
[false, {}, "Request failed: 503"],
[true, { status: "error", message: "Application rejected" }, "Application rejected"],
])("retains error precedence for HTTP ok=%s and %j", async (ok, data, message) => {
mockFetch.mockResolvedValue({ ok, status: 503, json: async () => data });
await expect(send()).rejects.toThrow(message);
});

it("propagates an invalid JSON response without retrying", async () => {
mockFetch.mockClear();
mockFetch.mockResolvedValue({
ok: false,
json: async () => { throw new SyntaxError("Invalid JSON"); },
});
await expect(send()).rejects.toThrow("Invalid JSON");
expect(mockFetch).toHaveBeenCalledTimes(1);
});
});
}
51 changes: 21 additions & 30 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,12 @@ export interface ApiResponse {
[key: string]: unknown;
}

export async function get(
path: string,
params?: Record<string, string>,
async function request(
url: URL,
options: Pick<RequestInit, "method" | "body">,
): Promise<ApiResponse> {
const baseUrl = getBaseUrl();
const url = new URL(path, baseUrl);
if (params) {
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== "") {
url.searchParams.set(key, value);
}
}
}

const response = await fetch(url.toString(), {
method: "GET",
...options,
headers: {
"x-api-key": getApiKey(),
"Content-Type": "application/json",
Expand All @@ -38,27 +28,28 @@ export async function get(
return data;
}

export async function get(
path: string,
params?: Record<string, string>,
): Promise<ApiResponse> {
const url = new URL(path, getBaseUrl());
if (params) {
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== "") {
url.searchParams.set(key, value);
}
}
}

return request(url, { method: "GET" });
}

export async function post(
path: string,
body: Record<string, unknown>,
): Promise<ApiResponse> {
const baseUrl = getBaseUrl();
const url = new URL(path, baseUrl);

const response = await fetch(url.toString(), {
return request(new URL(path, getBaseUrl()), {
method: "POST",
headers: {
"x-api-key": getApiKey(),
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});

const data: ApiResponse = await response.json();

if (!response.ok || data.status === "error") {
throw new Error(data.error || data.message || `Request failed: ${response.status}`);
}

return data;
}
Loading