Skip to content

Commit

Permalink
NextResponse: add .json static method (#31483)
Browse files Browse the repository at this point in the history
closes: #31196

This new API was suggested in a previous version of this feature:
#31024 (comment)

Co-authored-by: JJ Kasper <[email protected]>
  • Loading branch information
Kikobeats and ijjk authored Nov 16, 2021
1 parent af82de4 commit 593d943
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/next/server/web/spec-extension/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ export class NextResponse extends Response {
return this.cookie(name, '', { expires: new Date(1), path: '/', ...opts })
}

static json(body: any) {
return new NextResponse(JSON.stringify(body), {
headers: { 'content-type': 'application/json' },
})
}

static redirect(url: string | NextURL, status = 302) {
if (!REDIRECTS.has(status)) {
throw new RangeError(
Expand Down
54 changes: 54 additions & 0 deletions test/unit/web-runtime/next-response.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/* eslint-env jest */

import { Blob, File, FormData } from 'next/dist/compiled/formdata-node'
import { Crypto } from 'next/dist/server/web/sandbox/polyfills'
import { Response } from 'next/dist/server/web/spec-compliant/response'
import { Headers } from 'next/dist/server/web/spec-compliant/headers'
import * as streams from 'web-streams-polyfill/ponyfill'

beforeAll(() => {
global['Blob'] = Blob
global['crypto'] = new Crypto()
global['File'] = File
global['FormData'] = FormData
global['Headers'] = Headers
global['ReadableStream'] = streams.ReadableStream
global['TransformStream'] = streams.TransformStream
global['Response'] = Response
})

afterAll(() => {
delete global['Blob']
delete global['crypto']
delete global['File']
delete global['Headers']
delete global['FormData']
delete global['ReadableStream']
delete global['TransformStream']
})

const toJSON = async (response) => ({
body: await response.json(),
contentType: response.headers.get('content-type'),
})

it('automatically parses and formats JSON', async () => {
const { NextResponse } = await import(
'next/dist/server/web/spec-extension/response'
)

expect(await toJSON(NextResponse.json({ message: 'hello!' }))).toMatchObject({
contentType: 'application/json',
body: { message: 'hello!' },
})

expect(await toJSON(NextResponse.json(null))).toMatchObject({
contentType: 'application/json',
body: null,
})

expect(await toJSON(NextResponse.json(''))).toMatchObject({
contentType: 'application/json',
body: '',
})
})

0 comments on commit 593d943

Please sign in to comment.