fix(NextResponse.json): pass options (#35367)

This commit is contained in:
Kiko Beats 2022-04-16 05:23:42 +02:00 committed by GitHub
parent a2e65ac6d8
commit 8f8e497e1b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 2 deletions

View file

@ -67,9 +67,14 @@ export class NextResponse extends Response {
return this.cookie(name, '', { expires: new Date(1), path: '/', ...opts })
}
static json(body: any) {
static json(body: any, init?: ResponseInit) {
const { headers, ...responseInit } = init || {}
return new NextResponse(JSON.stringify(body), {
headers: { 'content-type': 'application/json' },
...responseInit,
headers: {
...headers,
'content-type': 'application/json',
},
})
}

View file

@ -30,6 +30,7 @@ afterAll(() => {
const toJSON = async (response) => ({
body: await response.json(),
contentType: response.headers.get('content-type'),
status: response.status,
})
it('automatically parses and formats JSON', async () => {
@ -42,6 +43,24 @@ it('automatically parses and formats JSON', async () => {
body: { message: 'hello!' },
})
expect(
await toJSON(NextResponse.json({ status: 'success' }, { status: 201 }))
).toMatchObject({
contentType: 'application/json',
body: { status: 'success' },
status: 201,
})
expect(
await toJSON(
NextResponse.json({ error: { code: 'bad_request' } }, { status: 400 })
)
).toMatchObject({
contentType: 'application/json',
body: { error: { code: 'bad_request' } },
status: 400,
})
expect(await toJSON(NextResponse.json(null))).toMatchObject({
contentType: 'application/json',
body: null,