fix(web): handle empty-body 201/204 responses in API client

This commit is contained in:
Munkherdene 2026-08-22 20:29:35 +08:00
parent 53755e9c3a
commit 9afb5fcee8
2 changed files with 9 additions and 2 deletions

View file

@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest"; import { describe, it, expect, vi, beforeEach } from "vitest";
import { apiGet } from "./client"; import { apiGet, apiSend } from "./client";
import { NetWorthSchema } from "./schemas"; import { NetWorthSchema } from "./schemas";
beforeEach(() => vi.restoreAllMocks()); beforeEach(() => vi.restoreAllMocks());
describe("apiGet", () => { describe("apiGet", () => {
@ -13,3 +13,9 @@ describe("apiGet", () => {
await expect(apiGet("/networth", NetWorthSchema)).rejects.toThrow(); await expect(apiGet("/networth", NetWorthSchema)).rejects.toThrow();
}); });
}); });
describe("apiSend", () => {
it("resolves to null on an empty-body 201 (e.g. POST /categories, POST /manual-assets)", async () => {
vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 201 })));
await expect(apiSend("POST", "/categories", { name: "Food" })).resolves.toBeNull();
});
});

View file

@ -21,7 +21,8 @@ async function req(method: string, path: string, body?: unknown): Promise<unknow
throw new ApiError(401, "unauthorized"); throw new ApiError(401, "unauthorized");
} }
if (!res.ok) throw new ApiError(res.status, await res.text()); if (!res.ok) throw new ApiError(res.status, await res.text());
return res.status === 204 ? null : res.json(); const text = await res.text();
return text ? JSON.parse(text) : null;
} }
export async function apiGet<T>(path: string, schema: z.ZodType<T>): Promise<T> { export async function apiGet<T>(path: string, schema: z.ZodType<T>): Promise<T> {