diff --git a/src/middleware/pretty-json/index.test.ts b/src/middleware/pretty-json/index.test.ts index e3742e49..03f6accf 100644 --- a/src/middleware/pretty-json/index.test.ts +++ b/src/middleware/pretty-json/index.test.ts @@ -31,4 +31,28 @@ describe('JSON pretty by Middleware', () => { "message": "Hono!" }`) }) + + it('Should return pretty JSON output when middleware received custom query', async () => { + const targetQuery = 'format' + + const app = new Hono() + app.use( + '*', + prettyJSON({ + query: targetQuery, + }) + ) + app.get('/', (c) => + c.json({ + message: 'Hono!', + }) + ) + + const prettyText = await (await app.request(`?${targetQuery}`)).text() + expect(prettyText).toBe(`{ + "message": "Hono!" +}`) + const nonPrettyText = await (await app.request('?pretty')).text() + expect(nonPrettyText).toBe('{"message":"Hono!"}') + }) }) diff --git a/src/middleware/pretty-json/index.ts b/src/middleware/pretty-json/index.ts index e15e7e4f..bc198e58 100644 --- a/src/middleware/pretty-json/index.ts +++ b/src/middleware/pretty-json/index.ts @@ -5,8 +5,18 @@ import type { MiddlewareHandler } from '../../types' -type prettyOptions = { - space: number +interface PrettyOptions { + /** + * Number of spaces for indentation. + * @default 2 + */ + space?: number + + /** + * Query conditions for when to Pretty. + * @default 'pretty' + */ + query?: string } /** @@ -14,8 +24,7 @@ type prettyOptions = { * * @see {@link https://hono.dev/docs/middleware/builtin/pretty-json} * - * @param {prettyOptions} [options] - The options for the pretty JSON middleware. - * @param {number} [options.space=2] - Number of spaces for indentation. + * @param options - The options for the pretty JSON middleware. * @returns {MiddlewareHandler} The middleware handler function. * * @example @@ -28,13 +37,14 @@ type prettyOptions = { * }) * ``` */ -export const prettyJSON = (options: prettyOptions = { space: 2 }): MiddlewareHandler => { +export const prettyJSON = (options?: PrettyOptions): MiddlewareHandler => { + const targetQuery = options?.query ?? 'pretty' return async function prettyJSON(c, next) { - const pretty = c.req.query('pretty') || c.req.query('pretty') === '' + const pretty = c.req.query(targetQuery) || c.req.query(targetQuery) === '' await next() if (pretty && c.res.headers.get('Content-Type')?.startsWith('application/json')) { const obj = await c.res.json() - c.res = new Response(JSON.stringify(obj, null, options.space), c.res) + c.res = new Response(JSON.stringify(obj, null, options?.space ?? 2), c.res) } } }