From f819d937b2a0afa42481c39200959c6ace7c9faf Mon Sep 17 00:00:00 2001 From: CJ Quines Date: Wed, 8 Jan 2025 13:19:08 -0500 Subject: [PATCH] feat(hono): let handlers use hono requests --- packages/hono/src/honoPlugin.test.ts | 25 +++++++++++++++++++++++++ packages/hono/src/honoPlugin.ts | 6 +++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/hono/src/honoPlugin.test.ts b/packages/hono/src/honoPlugin.test.ts index ac9023a3..01bdebe1 100644 --- a/packages/hono/src/honoPlugin.test.ts +++ b/packages/hono/src/honoPlugin.test.ts @@ -180,6 +180,15 @@ describe("hono passthrough", () => { throw new Error("arbitrary error"); }, }), + create: stl.endpoint({ + endpoint: "POST /api/posts", + body: z.any(), + response: z.any(), + handler: async (body, context) => { + const [c] = context.server.args; + return { bodyStl: body, bodyRaw: await c.req.raw.text() }; + }, + }), }, }), redirect: stl.resource({ @@ -235,4 +244,20 @@ describe("hono passthrough", () => { `"custom error: arbitrary error"` ); }); + + test("request passthrough", async () => { + const response = await app.request("/api/posts", { + method: "POST", + body: JSON.stringify({ message: "hello" }), + }); + expect(response).toHaveProperty("status", 200); + expect(await response.json()).toMatchInlineSnapshot(` + { + "bodyRaw": "{"message":"hello"}", + "bodyStl": { + "message": "hello", + }, + } + `); + }); }); diff --git a/packages/hono/src/honoPlugin.ts b/packages/hono/src/honoPlugin.ts index f31a14d1..87836029 100644 --- a/packages/hono/src/honoPlugin.ts +++ b/packages/hono/src/honoPlugin.ts @@ -77,7 +77,11 @@ function makeHandler(endpoints: AnyEndpoint[], options?: StlAppOptions) { const params = stl.initParams({ path, query: search ? qs.parse(search.replace(/^\?/, "")) : {}, - body: await c.req.json().catch(() => undefined), + // Don't use up the raw body in case the handler needs to use it: + body: await c.req.raw + .clone() + .json() + .catch(() => undefined), headers: c.req.header(), });