Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NextResponse: add .json static method #31483

Merged
merged 5 commits into from Nov 16, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/next/server/web/spec-extension/response.ts
Expand Up @@ -63,6 +63,12 @@ export class NextResponse extends Response {
return this.cookie(name, '', { expires: new Date(1), path: '/', ...opts })
}

static json(body: BodyInit | null) {
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
@@ -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: '',
})
})