File tree 2 files changed +35
-2
lines changed
2 files changed +35
-2
lines changed Original file line number Diff line number Diff line change @@ -12,13 +12,13 @@ const INTERNALS = Symbol('Response internals');
12
12
13
13
/**
14
14
* Response class
15
- *
15
+ *
16
16
* @typedef {Object } Ext
17
17
* @property {number } [size]
18
18
* @property {string } [url]
19
19
* @property {number } [counter]
20
20
* @property {number } [highWaterMark]
21
- *
21
+ *
22
22
* @implements {globalThis.Response}
23
23
*/
24
24
export default class Response extends Body {
@@ -126,6 +126,23 @@ export default class Response extends Body {
126
126
} ) ;
127
127
}
128
128
129
+ /**
130
+ * @param {any } data The URL that the new response is to originate from.
131
+ * @param {ResponseInit } [responseInit] An optional status code for the response (e.g., 302.)
132
+ * @returns {Response } A Response object.
133
+ */
134
+ static json ( data , responseInit = { } ) {
135
+ let headers = new Headers ( responseInit . headers ) ;
136
+ if ( ! headers . has ( "Content-Type" ) ) {
137
+ headers . set ( "Content-Type" , "application/json; charset=utf-8" ) ;
138
+ }
139
+
140
+ return new Response ( JSON . stringify ( data ) , {
141
+ ...responseInit ,
142
+ headers,
143
+ } ) ;
144
+ }
145
+
129
146
get [ Symbol . toStringTag ] ( ) {
130
147
return 'Response' ;
131
148
}
Original file line number Diff line number Diff line change @@ -5,6 +5,7 @@ import {Blob} from '@remix-run/web-blob';
5
5
import { Response } from '@remix-run/web-fetch' ;
6
6
import TestServer from './utils/server.js' ;
7
7
import { ReadableStream } from '../src/package.js' ;
8
+ import exp from 'constants' ;
8
9
9
10
const { expect} = chai ;
10
11
@@ -198,6 +199,21 @@ describe('Response', () => {
198
199
const res = new Response ( ) ;
199
200
expect ( res . url ) . to . equal ( '' ) ;
200
201
} ) ;
202
+
203
+ it ( 'should support json static method' , ( ) => {
204
+ const res = Response . json ( { a : 1 } ) ;
205
+ return res . json ( ) . then ( result => {
206
+ expect ( result . a ) . to . equal ( 1 ) ;
207
+ } ) ;
208
+ } )
209
+
210
+ it ( 'should support json static method with added responseInit' , ( ) => {
211
+ const res = Response . json ( { a : 1 } , { headers : { "x-foo" : "bar" } } ) ;
212
+ expect ( res . headers . get ( 'x-foo' ) ) . to . equal ( 'bar' ) ;
213
+ return res . json ( ) . then ( result => {
214
+ expect ( result . a ) . to . equal ( 1 ) ;
215
+ } ) ;
216
+ } )
201
217
} ) ;
202
218
203
219
const streamFromString = text => new ReadableStream ( {
You can’t perform that action at this time.
0 commit comments