From 5c4dcd1d50301fcb99bd764386b8424765af4111 Mon Sep 17 00:00:00 2001 From: javad mnjd Date: Mon, 10 Jul 2023 18:01:46 +0330 Subject: [PATCH] feat: support blob responses (#422) --- src/app.ts | 9 +++++++++ test/app.test.ts | 20 ++++++++++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/app.ts b/src/app.ts index 1520fcb9..c06d716b 100644 --- a/src/app.ts +++ b/src/app.ts @@ -135,6 +135,15 @@ export function createAppEventHandler(stack: Stack, options: AppOptions) { return send(event, val); } + // Blob + if (val.arrayBuffer && typeof val.arrayBuffer === "function") { + return send( + event, + Buffer.from(await (val as Blob).arrayBuffer()), + val.type + ); + } + // Error if (val instanceof Error) { throw createError(val); diff --git a/test/app.test.ts b/test/app.test.ts index df56deb8..2886cc5a 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -10,8 +10,9 @@ import { createError, } from "../src"; -const readableStreamSupported = - typeof ReadableStream !== "undefined"; /* Node.js 16 */ +// Node.js 16 limitations +const readableStreamSupported = typeof ReadableStream !== "undefined"; +const blobSupported = typeof Blob !== "undefined"; describe("app", () => { let app: App; @@ -55,6 +56,21 @@ describe("app", () => { } }); + it.runIf(blobSupported)("can return Blob directly", async () => { + app.use( + eventHandler( + () => + new Blob(["

Hello World

"], { + type: "text/html", + }) + ) + ); + const res = await request.get("/"); + + expect(res.headers["content-type"]).toBe("text/html"); + expect(res.text).toBe("

Hello World

"); + }); + it("can return Buffer directly", async () => { app.use(eventHandler(() => Buffer.from("

Hello world!

", "utf8"))); const res = await request.get("/");