diff --git a/src/middleware/with-response-object-check.ts b/src/middleware/with-response-object-check.ts index 9f8cae0..af5f8db 100644 --- a/src/middleware/with-response-object-check.ts +++ b/src/middleware/with-response-object-check.ts @@ -8,7 +8,10 @@ export const withResponseObjectCheck: Middleware< > = async (req, ctx, next) => { const rawResponse = await next(req, ctx) - if (typeof rawResponse === "object" && !(rawResponse instanceof Response)) { + if ( + (typeof rawResponse === "object" && !(rawResponse instanceof Response)) || + typeof rawResponse === "function" + ) { throw new Error( "Use ctx.json({...}) instead of returning an object directly." ) diff --git a/tests/errors/do-not-allow-raw-json.test.ts b/tests/errors/do-not-allow-raw-json.test.ts index 8682796..7451c91 100644 --- a/tests/errors/do-not-allow-raw-json.test.ts +++ b/tests/errors/do-not-allow-raw-json.test.ts @@ -37,3 +37,39 @@ test("should throw an error when responding with raw JSON", async (t) => { ) ) }) + +test("should throw an error when responding with a function", async (t) => { + const { axios } = await getTestRoute(t, { + globalSpec: { + authMiddleware: {}, + beforeAuthMiddleware: [ + async (req, ctx, next) => { + try { + return await next(req, ctx) + } catch (e: any) { + console.error(e) + return Response.json({ error: e.message }, { status: 500 }) + } + }, + ], + }, + routeSpec: { + methods: ["GET"], + jsonBody: z.any(), + jsonResponse: z.any(), + }, + routePath: "/", + routeFn: (req, ctx) => { + return (() => ({ foo: "bar" })) as any + }, + }) + + const { data } = await axios.get("/", { + validateStatus: () => true, + }) + t.true( + data.error.includes( + "Use ctx.json({...}) instead of returning an object directly" + ) + ) +})