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
2 changes: 2 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ export function createAppEventHandler(stack: Stack, options: AppOptions) {
) {
if (val.buffer) {
return send(event, val);
} else if (val instanceof Blob) {
return send(event, Buffer.from(await val.arrayBuffer()), val.type);
} else if (val instanceof Error) {
throw createError(val);
} else {
Expand Down
8 changes: 5 additions & 3 deletions src/utils/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,11 @@ export async function sendProxy(
return event.node.res.end(data);
}

// Send as stream
for await (const chunk of response.body as any as AsyncIterable<Uint8Array>) {
event.node.res.write(chunk);
if (response.body) {
// Send as stream
for await (const chunk of response.body as any as AsyncIterable<Uint8Array>) {
event.node.res.write(chunk);
}
}
return event.node.res.end();
}
Expand Down
14 changes: 14 additions & 0 deletions test/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,20 @@ describe("app", () => {
}
});

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

expect(res.text).toBe("Hello World");
});

it("can return Buffer directly", async () => {
app.use(eventHandler(() => Buffer.from("<h1>Hello world!</h1>", "utf8")));
const res = await request.get("/");
Expand Down
25 changes: 25 additions & 0 deletions test/proxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
setHeader,
readRawBody,
setCookie,
setResponseStatus,
} from "../src";
import { sendProxy, proxyRequest } from "../src/utils/proxy";

Expand Down Expand Up @@ -106,6 +107,30 @@ describe("", () => {
}
`);
});

it("can handle empty 304 responses", async () => {
app.use(
"/reply-empty-304",
eventHandler((event) => {
setResponseStatus(event, 304);
return "";
})
);

app.use(
"/",
eventHandler((event) => {
return proxyRequest(event, url + "/reply-empty-304", { fetch });
})
);

const result = await fetch(url + "/", {
method: "GET",
});

expect(result).toBeTruthy();
expect(result!.status).toBe(304);
});
});

describe("multipleCookies", () => {
Expand Down