Skip to content

Commit 71f8020

Browse files
committed
feat(request): -J and --json option
fix indexOf to regular expressions Signed-off-by: ysknsid25 <kengo071225@gmail.com>
1 parent d40462d commit 71f8020

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

src/commands/request/index.test.ts

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -779,4 +779,57 @@ describe('requestCommand', () => {
779779

780780
expect(consoleLogSpy).toHaveBeenCalledWith(expectedOutput)
781781
})
782+
783+
describe('Content-Type JSON detection', () => {
784+
const jsonString = '{"foo":"bar"}'
785+
const formattedJsonString = JSON.stringify(JSON.parse(jsonString), null, 2)
786+
787+
const matchingTypes = [
788+
'application/json',
789+
'APPLICATION/JSON',
790+
'application/json; charset=utf-8',
791+
'application/json; charset=UTF-8; boundary=something',
792+
'application/ld+json',
793+
'application/hal+json',
794+
'application/vnd.api+json',
795+
'application/merge-patch+json',
796+
'application/problem+json',
797+
'application/geo+json',
798+
]
799+
800+
const nonMatchingTypes = [
801+
'application/jsonx',
802+
'application/jsonapi',
803+
'application/json+ld',
804+
'application/json+hal',
805+
'text/json',
806+
'text/plain',
807+
'application/xml',
808+
'text/plain; application/json',
809+
]
810+
811+
matchingTypes.forEach((contentType) => {
812+
it(`should format JSON for Content-Type: ${contentType}`, async () => {
813+
const mockApp = new Hono()
814+
mockApp.get('/test', (c) => c.body(jsonString, 200, { 'Content-Type': contentType }))
815+
setupBasicMocks('test-app.js', mockApp)
816+
817+
await program.parseAsync(['node', 'test', 'request', '-P', '/test', 'test-app.js'])
818+
819+
expect(consoleLogSpy).toHaveBeenCalledWith(formattedJsonString)
820+
})
821+
})
822+
823+
nonMatchingTypes.forEach((contentType) => {
824+
it(`should NOT format JSON for Content-Type: ${contentType}`, async () => {
825+
const mockApp = new Hono()
826+
mockApp.get('/test', (c) => c.body(jsonString, 200, { 'Content-Type': contentType }))
827+
setupBasicMocks('test-app.js', mockApp)
828+
829+
await program.parseAsync(['node', 'test', 'request', '-P', '/test', 'test-app.js'])
830+
831+
expect(consoleLogSpy).toHaveBeenCalledWith(jsonString)
832+
})
833+
})
834+
})
782835
})

src/commands/request/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ const formatResponseBody = (
222222
contentType: string | undefined,
223223
jsonOption: boolean
224224
): string | object => {
225-
if (contentType && contentType.indexOf('application/json') !== -1) {
225+
if (contentType && /^application\/(json|[^;\s]+\+json)($|;)/i.test(contentType)) {
226226
try {
227227
const parsedJSON = JSON.parse(responseBody)
228228
if (jsonOption) {

0 commit comments

Comments
 (0)