Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support blob responses #422

Merged
merged 17 commits into from
Jul 10, 2023
Merged
9 changes: 9 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
20 changes: 18 additions & 2 deletions test/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -55,6 +56,21 @@ describe("app", () => {
}
});

it.runIf(blobSupported)("can return Blob directly", async () => {
app.use(
eventHandler(
() =>
new Blob(["<h1>Hello World</h1>"], {
type: "text/html",
})
)
);
const res = await request.get("/");

expect(res.headers["content-type"]).toBe("text/html");
expect(res.text).toBe("<h1>Hello World</h1>");
});

it("can return Buffer directly", async () => {
app.use(eventHandler(() => Buffer.from("<h1>Hello world!</h1>", "utf8")));
const res = await request.get("/");
Expand Down