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
6 changes: 6 additions & 0 deletions src/middleware/http-exceptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,9 @@ export class ResponseValidationError extends WinterSpecMiddlewareError {
super(formatZodError(error), 500)
}
}

export class ResponseObjectNotAllowedError extends WinterSpecMiddlewareError {
constructor() {
super("Use ctx.json({...}) instead of returning an object directly.", 500)
}
}
6 changes: 2 additions & 4 deletions src/middleware/with-response-object-check.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ResponseValidationError } from "./http-exceptions.js"
import { ResponseObjectNotAllowedError } from "./http-exceptions.js"
import { Middleware } from "./types.js"
import { RouteSpec } from "src/types/route-spec.js"

Expand All @@ -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."
)
throw new ResponseObjectNotAllowedError()
}

return rawResponse
Expand Down
39 changes: 39 additions & 0 deletions tests/middleware/with-response-object-check.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import test from "ava"
import { z } from "zod"
import { getTestRoute } from "../fixtures/get-test-route.js"
import { createWithDefaultExceptionHandling } from "../../src/middleware/with-default-exception-handling.js"

test("returning a plain object with jsonResponse validation under default exception handling", async (t) => {
const { axios } = await getTestRoute(t, {
globalSpec: {
authMiddleware: {},
beforeAuthMiddleware: [createWithDefaultExceptionHandling()],
},
routeSpec: {
auth: "none",
methods: ["GET"],
jsonResponse: z.object({
ok: z.boolean(),
message: z.string(),
}),
},
routeFn: (_, ctx) => {
// Accidental plain object return
return { ok: true, message: "hello" } as any
},
routePath: "/test-plain-object",
})

const response = await axios.get("/test-plain-object", {
validateStatus: () => true,
})

console.log("Response status:", response.status)
console.log("Response data:", response.data)

t.is(response.status, 500)
t.is(
response.data.message,
"Use ctx.json({...}) instead of returning an object directly."
)
})
Loading