File tree Expand file tree Collapse file tree 2 files changed +34
-2
lines changed
Expand file tree Collapse file tree 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');
1212
1313/**
1414 * Response class
15- *
15+ *
1616 * @typedef {Object } Ext
1717 * @property {number } [size]
1818 * @property {string } [url]
1919 * @property {number } [counter]
2020 * @property {number } [highWaterMark]
21- *
21+ *
2222 * @implements {globalThis.Response}
2323 */
2424export default class Response extends Body {
@@ -126,6 +126,23 @@ export default class Response extends Body {
126126 } ) ;
127127 }
128128
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+
129146 get [ Symbol . toStringTag ] ( ) {
130147 return 'Response' ;
131148 }
Original file line number Diff line number Diff line change @@ -198,6 +198,21 @@ describe('Response', () => {
198198 const res = new Response ( ) ;
199199 expect ( res . url ) . to . equal ( '' ) ;
200200 } ) ;
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+ } )
201216} ) ;
202217
203218const streamFromString = text => new ReadableStream ( {
You can’t perform that action at this time.
0 commit comments