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
2 changes: 2 additions & 0 deletions src/create-with-winter-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { withInputValidation } from "./middleware/with-input-validation.js"
import { withUnhandledExceptionHandling } from "./middleware/with-unhandled-exception-handling.js"
import { ResponseValidationError } from "./middleware/http-exceptions.js"
import { withResponseObjectCheck } from "./middleware/with-response-object-check.js"
import { assertValidRouteReturnValue } from "./middleware/route-return-value-error.js"

const attachMetadataToRouteFn = <
const GS extends GlobalSpec,
Expand Down Expand Up @@ -126,6 +127,7 @@ function serializeResponse(
): Middleware {
return async (req, ctx, next) => {
const rawResponse = await next(req, ctx)
assertValidRouteReturnValue(rawResponse)

const statusCode =
rawResponse instanceof WinterSpecResponse
Expand Down
17 changes: 17 additions & 0 deletions src/middleware/route-return-value-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const INVALID_ROUTE_RETURN_VALUE_MESSAGE =
"Use ctx.json({...}) instead of returning an object directly."

export function isValidRouteReturnValue(value: unknown): boolean {
return (
value instanceof Response ||
(typeof value === "object" &&
value !== null &&
"serializeToResponse" in value)
)
}

export function assertValidRouteReturnValue(value: unknown) {
if (!isValidRouteReturnValue(value)) {
throw new Error(INVALID_ROUTE_RETURN_VALUE_MESSAGE)
}
}
5 changes: 2 additions & 3 deletions src/middleware/with-response-object-check.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ResponseValidationError } from "./http-exceptions.js"
import { Middleware } from "./types.js"
import { RouteSpec } from "src/types/route-spec.js"
import { INVALID_ROUTE_RETURN_VALUE_MESSAGE } from "./route-return-value-error.js"

export const withResponseObjectCheck: Middleware<
{ routeSpec: RouteSpec<any> },
Expand All @@ -9,9 +10,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 Error(INVALID_ROUTE_RETURN_VALUE_MESSAGE)
}

return rawResponse
Expand Down
46 changes: 46 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,49 @@ test("should throw an error when responding with raw JSON", async (t) => {
)
)
})

const invalidReturnCases = [
{ name: "undefined", value: undefined },
{ name: "null", value: null },
{ name: "string", value: "not a response" },
{ name: "number", value: 42 },
{ name: "boolean", value: true },
{ name: "bigint", value: BigInt(42) },
{ name: "symbol", value: Symbol("not-a-response") },
{ name: "function", value: () => "not a response" },
]

for (const { name, value } of invalidReturnCases) {
test(`should throw ctx.json guidance when route returns ${name}`, async (t) => {
const { axios } = await getTestRoute(t, {
globalSpec: {
authMiddleware: {},
beforeAuthMiddleware: [
async (req, ctx, next) => {
try {
return await next(req, ctx)
} catch (e: any) {
return Response.json({ error: e.message }, { status: 500 })
}
},
],
},
routeSpec: {
methods: ["GET"],
jsonBody: z.any(),
jsonResponse: z.any(),
},
routePath: "/",
routeFn: () => value as any,
})

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