index.ts
This file
Path
src/middleware/pretty-json/index.ts
68 lines 路 1.9 KiB 路 TypeScript
Last changed by
fix(pretty-json): don't break responses with unparseable JSON bodies (#5377)Neil Daquioagbefore adoptionf950277
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869/** * @module * Pretty JSON Middleware for Hono. */
import type { MiddlewareHandler } from '../../types'
interface PrettyOptions { /** * Number of spaces for indentation. * @default 2 */ space?: number
/** * Query conditions for when to Pretty. * @default 'pretty' */ query?: string
/** * Force prettification of JSON responses regardless of query parameters. * @default false */ force?: boolean}
const jsonContentTypeRegex = /^application\/(?:[a-z0-9._-]+\+)?json(?=$|[;\s])/i
/** * Pretty JSON Middleware for Hono. * * @see {@link https://hono.dev/docs/middleware/builtin/pretty-json} * * @param options - The options for the pretty JSON middleware. * @returns {MiddlewareHandler} The middleware handler function. * * @example * ```ts * const app = new Hono() * * app.use(prettyJSON()) // With options: prettyJSON({ space: 4 }) * app.get('/', (c) => { * return c.json({ message: 'Hono!' }) * }) * ``` */export const prettyJSON = (options?: PrettyOptions): MiddlewareHandler => { const targetQuery = options?.query ?? 'pretty' return async function prettyJSON(c, next) { const pretty = options?.force || c.req.query(targetQuery) || c.req.query(targetQuery) === '' await next() const contentType = c.res.headers.get('Content-Type') if (pretty && contentType && jsonContentTypeRegex.test(contentType)) { // Read from a clone so that the response is kept intact when the body is not parseable as JSON let obj: unknown try { obj = await c.res.clone().json() } catch { // e.g. an empty 204 response or a body that is not valid JSON return } c.res = new Response(JSON.stringify(obj, null, options?.space ?? 2), c.res) // The length of the body has changed, so remove the stale Content-Length c.res.headers.delete('Content-Length') } }}