File tree 2 files changed +34
-2
lines changed
2 files changed +34
-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 @@ -220,6 +220,21 @@ describe('Response', () => {
220
220
const res = new Response ( ) ;
221
221
expect ( res . url ) . to . equal ( '' ) ;
222
222
} ) ;
223
+
224
+ it ( 'should support json static method' , ( ) => {
225
+ const res = Response . json ( { a : 1 } ) ;
226
+ return res . json ( ) . then ( result => {
227
+ expect ( result . a ) . to . equal ( 1 ) ;
228
+ } ) ;
229
+ } )
230
+
231
+ it ( 'should support json static method with added responseInit' , ( ) => {
232
+ const res = Response . json ( { a : 1 } , { headers : { "x-foo" : "bar" } } ) ;
233
+ expect ( res . headers . get ( 'x-foo' ) ) . to . equal ( 'bar' ) ;
234
+ return res . json ( ) . then ( result => {
235
+ expect ( result . a ) . to . equal ( 1 ) ;
236
+ } ) ;
237
+ } )
223
238
} ) ;
224
239
225
240
const streamFromString = text => new ReadableStream ( {
You can’t perform that action at this time.
0 commit comments