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
4 changes: 1 addition & 3 deletions src/middleware/with-response-object-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ export const withResponseObjectCheck: Middleware<
const rawResponse = await next(req, ctx)

if (typeof rawResponse === "object" && !(rawResponse instanceof Response)) {
throw new Error(
"Use ctx.json({...}) instead of returning an object directly."
)
return Response.json(rawResponse)
}

return rawResponse
Expand Down
23 changes: 4 additions & 19 deletions tests/errors/do-not-allow-raw-json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,10 @@ import test from "ava"
import { z } from "zod"
import { getTestRoute } from "tests/fixtures/get-test-route.js"

test("should throw an error when responding with raw JSON", async (t) => {
test("should auto-wrap plain object returns in Response.json()", 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"],
Expand All @@ -28,12 +18,7 @@ test("should throw an error when responding with raw JSON", async (t) => {
},
})

const { data } = await axios.get("/", {
validateStatus: () => true,
})
t.true(
data.error.includes(
"Use ctx.json({...}) instead of returning an object directly"
)
)
const { data, status } = await axios.get("/")
t.is(status, 200)
t.is(data.foo, "bar")
})
Loading