Created
February 3, 2025 05:02
-
-
Save gregfromstl/70c1cd540e346974b08bfc9c833f453d to your computer and use it in GitHub Desktop.
Hono middleware for strinfigying BigInt types in responses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createMiddleware } from "hono/factory"; | |
import type { | |
InvalidJSONValue, | |
JSONValue, | |
SimplifyDeepArray, | |
} from "hono/utils/types"; | |
export const transformJsonResponse = createMiddleware(async (ctx, next) => { | |
const originalJson = ctx.json.bind(ctx); | |
type JsonFn = ( | |
obj: JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue, | |
init?: ResponseInit, | |
) => Response; | |
(ctx.json as JsonFn) = ( | |
obj: JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue, | |
init?: ResponseInit, | |
) => { | |
const json = JSON.stringify(obj, (_key, value) => { | |
if (typeof value === "bigint") return value.toString(); | |
return value; | |
}); | |
return originalJson(JSON.parse(json), init); | |
}; | |
await next(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment