Files
SnowLuma/.pnpm-store/v11/files/b5/f2b811f389800aab37bdd9df86f325fe9910e6469afd7ae3e5598ba913ce007069fd8c796b00bc6a6397e5e63198f9278eaa0fc7bfa43875178656c82f2514
T
TanTan 2a69b23b47
Dev Build / cleanup (push) Waiting to run
Dev Build / typecheck (push) Waiting to run
docs: 仓库链接指向本镜像仓库
2026-11-13 09:27:07 +08:00

41 lines
1.2 KiB
Plaintext

//#region src/middleware/pretty-json/index.ts
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!' })
* })
* ```
*/
const prettyJSON = (options) => {
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)) {
let obj;
try {
obj = await c.res.clone().json();
} catch {
return;
}
c.res = new Response(JSON.stringify(obj, null, options?.space ?? 2), c.res);
c.res.headers.delete("Content-Length");
}
};
};
//#endregion
export { prettyJSON };