Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/middleware/with-response-object-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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."
)
Expand Down
36 changes: 36 additions & 0 deletions tests/errors/do-not-allow-raw-json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
)
})