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 @@ -198,6 +198,21 @@ describe('Response', () => {
198
198
const res = new Response ( ) ;
199
199
expect ( res . url ) . to . equal ( '' ) ;
200
200
} ) ;
201
+
202
+ it ( 'should support json static method' , ( ) => {
203
+ const res = Response . json ( { a : 1 } ) ;
204
+ return res . json ( ) . then ( result => {
205
+ expect ( result . a ) . to . equal ( 1 ) ;
206
+ } ) ;
207
+ } )
208
+
209
+ it ( 'should support json static method with added responseInit' , ( ) => {
210
+ const res = Response . json ( { a : 1 } , { headers : { "x-foo" : "bar" } } ) ;
211
+ expect ( res . headers . get ( 'x-foo' ) ) . to . equal ( 'bar' ) ;
212
+ return res . json ( ) . then ( result => {
213
+ expect ( result . a ) . to . equal ( 1 ) ;
214
+ } ) ;
215
+ } )
201
216
} ) ;
202
217
203
218
const streamFromString = text => new ReadableStream ( {
You can’t perform that action at this time.
0 commit comments