Skip to content
Closed
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
13 changes: 13 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)
assertResponseWasReturned(rawResponse)

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

function assertResponseWasReturned(
rawResponse: unknown
): asserts rawResponse is SerializableToResponse | Response {
if (rawResponse == null || typeof rawResponse !== "object") {
throw new Error(
`Use ctx.json({...}) or return a Response instead of returning ${String(
rawResponse
)} directly.`
)
}
}

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

test("should throw a helpful 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"],
jsonResponse: z.any(),
},
routePath: "/",
routeFn: (() => undefined) as any,
})

const { data } = await axios.get("/", {
validateStatus: () => true,
})
t.true(data.error.includes("returning undefined directly"))
})
Loading