Unverified Commit 593d943c authored by Kiko Beats's avatar Kiko Beats Committed by GitHub

NextResponse: add `.json` static method (#31483)

closes: https://github.com/vercel/next.js/issues/31196

This new API was suggested in a previous version of this feature:
https://github.com/vercel/next.js/pull/31024#discussion_r745035448Co-authored-by: 's avatarJJ Kasper <22380829+ijjk@users.noreply.github.com>
parent af82de42
......@@ -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(
......
/* 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: '',
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment