aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Effect/requestBody.test.ts
blob: 8ca3103652d5ea96cb56beb087bd15bd14aff92b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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 });
	});
});