From 6a44eac70c41bb1343a20ddf3ce775e416214d75 Mon Sep 17 00:00:00 2001 From: Fuwn Date: Tue, 3 Mar 2026 09:04:44 -0800 Subject: refactor(effect): add request body schema decoders to api routes --- src/lib/Effect/requestBody.test.ts | 56 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/lib/Effect/requestBody.test.ts (limited to 'src/lib/Effect/requestBody.test.ts') diff --git a/src/lib/Effect/requestBody.test.ts b/src/lib/Effect/requestBody.test.ts new file mode 100644 index 00000000..8ca31036 --- /dev/null +++ b/src/lib/Effect/requestBody.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vitest"; +import { Schema } from "effect"; +import { + decodeRequestJsonOrThrow, + decodeUnknownOrThrow, +} from "$lib/Effect/requestBody"; + +describe("request body effect decoders", () => { + it("decodes unknown payload with a schema", () => { + const decoded = decodeUnknownOrThrow(Schema.Array(Schema.String), [ + "a", + "b", + "c", + ]); + + expect(decoded).toEqual(["a", "b", "c"]); + }); + + it("throws when payload does not match schema", () => { + expect(() => + decodeUnknownOrThrow(Schema.Array(Schema.String), ["a", 2]), + ).toThrowError(); + }); + + it("decodes request.json body with schema", async () => { + const request = new Request("https://due.moe/api/preferences", { + method: "PUT", + headers: { + "content-type": "application/json", + }, + body: JSON.stringify(["seasonal", "ongoing"]), + }); + const decoded = await decodeRequestJsonOrThrow( + request, + Schema.Array(Schema.String), + ); + + expect(decoded).toEqual(["seasonal", "ongoing"]); + }); + + it("decodes request.json object body with record schema", async () => { + const request = new Request("https://due.moe/api/configuration", { + method: "PUT", + headers: { + "content-type": "application/json", + }, + body: JSON.stringify({ theme: "dark", notifications: true }), + }); + const decoded = await decodeRequestJsonOrThrow( + request, + Schema.Record(Schema.String, Schema.Unknown), + ); + + expect(decoded).toEqual({ theme: "dark", notifications: true }); + }); +}); -- cgit v1.2.3