Fix invalid feed characters (#31)

This commit is contained in:
Olav Sundfør 2024-04-14 12:16:00 +02:00 committed by GitHub
parent 29cb0addd7
commit eb4304da71
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 24 additions and 5 deletions

16
lib/utils.test.ts Normal file
View File

@ -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 = "<message>Hello, World!</message>";
const response = responseXML(body, 200);
const responseBody = await response.text();
assertEquals(responseBody, body);
assertNotEquals(responseBody, JSON.stringify(body));
});

View File

@ -14,15 +14,16 @@ type EnumValues<T> = T[keyof T];
type Status = EnumValues<typeof STATUS_CODE>; type Status = EnumValues<typeof STATUS_CODE>;
export function responseJSON(body: unknown | null, status: Status) { 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"); return response(body, status, "xml");
} }
function response(body: unknown | null, status: number, type: "json" | "xml") { function response(body: string, status: number, type: "json" | "xml") {
return new Response(JSON.stringify(body), { return new Response(body, {
status, status,
headers: { headers: {
"Content-Type": `application/${type}`, "Content-Type": `application/${type}`,

View File

@ -12,5 +12,7 @@ export const handler = async (_req: Request, ctx: FreshContext): Promise<Respons
} }
const feed = rss.assembleFeed(series); const feed = rss.assembleFeed(series);
return responseXML(feed, STATUS_CODE.OK); const xml = responseXML(feed, STATUS_CODE.OK);
return xml;
}; };