From eb4304da715bf024b1d68ff785580c435e4a6ac3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20Sundf=C3=B8r?= Date: Sun, 14 Apr 2024 12:16:00 +0200 Subject: [PATCH] Fix invalid feed characters (#31) --- lib/utils.test.ts | 16 ++++++++++++++++ lib/utils.ts | 9 +++++---- routes/api/feeds/[seriesId].ts | 4 +++- 3 files changed, 24 insertions(+), 5 deletions(-) create mode 100644 lib/utils.test.ts diff --git a/lib/utils.test.ts b/lib/utils.test.ts new file mode 100644 index 0000000..903ee45 --- /dev/null +++ b/lib/utils.test.ts @@ -0,0 +1,16 @@ +import { assertEquals, assertNotEquals } from "$std/assert/mod.ts"; +import { responseJSON, responseXML } from "./utils.ts"; + +Deno.test("JSON response is stringified", async () => { + const body = { message: "Hello, World!" }; + const response = responseJSON(body, 200); + assertEquals(await response.text(), JSON.stringify(body)); +}); + +Deno.test("XML resopnse is _not_ stringified", async () => { + const body = "Hello, World!"; + const response = responseXML(body, 200); + const responseBody = await response.text(); + assertEquals(responseBody, body); + assertNotEquals(responseBody, JSON.stringify(body)); +}); diff --git a/lib/utils.ts b/lib/utils.ts index f75af7a..586c836 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -14,15 +14,16 @@ type EnumValues = T[keyof T]; type Status = EnumValues; export function responseJSON(body: unknown | null, status: Status) { - return response(body, status, "json"); + const stringifiedBody = JSON.stringify(body); + return response(stringifiedBody, status, "json"); } -export function responseXML(body: unknown | null, status: Status) { +export function responseXML(body: string, status: Status) { return response(body, status, "xml"); } -function response(body: unknown | null, status: number, type: "json" | "xml") { - return new Response(JSON.stringify(body), { +function response(body: string, status: number, type: "json" | "xml") { + return new Response(body, { status, headers: { "Content-Type": `application/${type}`, diff --git a/routes/api/feeds/[seriesId].ts b/routes/api/feeds/[seriesId].ts index 39e5161..d480386 100644 --- a/routes/api/feeds/[seriesId].ts +++ b/routes/api/feeds/[seriesId].ts @@ -12,5 +12,7 @@ export const handler = async (_req: Request, ctx: FreshContext): Promise