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
27 changes: 27 additions & 0 deletions src/create-with-winter-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ function serializeResponse(
): Middleware {
return async (req, ctx, next) => {
const rawResponse = await next(req, ctx)
assertValidResponseValue(rawResponse)

const statusCode =
rawResponse instanceof WinterSpecResponse
Expand All @@ -150,6 +151,32 @@ function serializeResponse(
}
}

function assertValidResponseValue(rawResponse: unknown): asserts rawResponse is SerializableToResponse | Response {
if (rawResponse == null) {
throw new Error(
"Route handlers must return a Response. If you are returning JSON, use ctx.json({...})."
)
}

if (typeof rawResponse === "object") {
if (
rawResponse instanceof Response ||
rawResponse instanceof WinterSpecResponse ||
"serializeToResponse" in rawResponse
) {
return
}

throw new Error(
"Use ctx.json({...}) instead of returning an object directly."
)
}

throw new Error(
"Route handlers must return a Response. If you are returning JSON, use ctx.json({...})."
)
}

export async function wrapMiddlewares(
middlewares: MiddlewareChain,
routeFn: WinterSpecRouteFn<any, any, any>,
Expand Down
34 changes: 34 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,37 @@ test("should throw an error when responding with raw JSON", async (t) => {
)
)
})

test("should throw a clear error when route returns undefined", 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: () => undefined as any,
})

const { data } = await axios.get("/", {
validateStatus: () => true,
})

t.true(
data.error.includes(
"Route handlers must return a Response. If you are returning JSON, use ctx.json({...})."
)
)
})