0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-24 11:07:29 +01:00

feat(pretty-json): support custom query (#3300)

* feat(pretty-json): support custom query

* feat: don't use default value
This commit is contained in:
Shotaro Nakamura 2024-08-26 21:18:36 +09:00 committed by GitHub
parent 33189b8765
commit 7ad1f05926
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 41 additions and 7 deletions

View File

@ -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!"}')
})
})

View File

@ -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)
}
}
}