H
Hono2mo ago
duydang

Using both `c.body` and `c.json` in an endpoint results in `response.json()` of `Promise<unknown>`

hi everyone, is there any way to get the response type working when i have endpoints that return multiple type of content based on status code? this is an example where it fails to infer the type
export const routes = new Hono()
.get(
'/hello',
(c) => {
if (Math.random() > 0.5) {
return c.body(null, 204); // c.json(null, 204) will get the types to work but Response constructor: Invalid response status code 204 runtime error
}
return c.json({ hello: 'world' }, 200);
}
);

const response = await rpc.api.hello.$get();
const json = await response.json();
// ^^^^ unknown
export const routes = new Hono()
.get(
'/hello',
(c) => {
if (Math.random() > 0.5) {
return c.body(null, 204); // c.json(null, 204) will get the types to work but Response constructor: Invalid response status code 204 runtime error
}
return c.json({ hello: 'world' }, 200);
}
);

const response = await rpc.api.hello.$get();
const json = await response.json();
// ^^^^ unknown
1 Reply
capedcoder
capedcoder2mo ago
A null body is not json, it's an empty body. You first need to check to see if the response is JSON, then you can read the json if it exists. Something like this:
app.get("/test", (c) => {
if (Math.random() < 0.5) return c.body(null, 204);
return c.json({ status: "ok" }, 200);
});

const response = await app.request("/test");
const isJson = response.headers.get("content-type")?.startsWith("application/json") || false;
if (isJson) {
console.log(await response.json());
}
app.get("/test", (c) => {
if (Math.random() < 0.5) return c.body(null, 204);
return c.json({ status: "ok" }, 200);
});

const response = await app.request("/test");
const isJson = response.headers.get("content-type")?.startsWith("application/json") || false;
if (isJson) {
console.log(await response.json());
}
Want results from more Discord servers?
Add your server