diff --git a/packages/fetch/src/response.js b/packages/fetch/src/response.js index ebeba7c..917efc0 100644 --- a/packages/fetch/src/response.js +++ b/packages/fetch/src/response.js @@ -12,13 +12,13 @@ const INTERNALS = Symbol('Response internals'); /** * Response class - * + * * @typedef {Object} Ext * @property {number} [size] * @property {string} [url] * @property {number} [counter] * @property {number} [highWaterMark] - * + * * @implements {globalThis.Response} */ export default class Response extends Body { @@ -126,6 +126,23 @@ export default class Response extends Body { }); } + /** + * @param {any} data The URL that the new response is to originate from. + * @param {ResponseInit} [responseInit] An optional status code for the response (e.g., 302.) + * @returns {Response} A Response object. + */ + static json(data, responseInit = {}) { + let headers = new Headers(responseInit.headers); + if (!headers.has("Content-Type")) { + headers.set("Content-Type", "application/json; charset=utf-8"); + } + + return new Response(JSON.stringify(data), { + ...responseInit, + headers, + }); + } + get [Symbol.toStringTag]() { return 'Response'; } diff --git a/packages/fetch/test/response.js b/packages/fetch/test/response.js index 686b740..d66830d 100644 --- a/packages/fetch/test/response.js +++ b/packages/fetch/test/response.js @@ -198,6 +198,21 @@ describe('Response', () => { const res = new Response(); expect(res.url).to.equal(''); }); + + it('should support json static method', () => { + const res = Response.json({a: 1}); + return res.json().then(result => { + expect(result.a).to.equal(1); + }); + }) + + it('should support json static method with added responseInit', () => { + const res = Response.json({a: 1}, { headers: { "x-foo": "bar" } }); + expect(res.headers.get('x-foo')).to.equal('bar'); + return res.json().then(result => { + expect(result.a).to.equal(1); + }); + }) }); const streamFromString = text => new ReadableStream({