Skip to content

Commit

Permalink
feat: add Response.json static method
Browse files Browse the repository at this point in the history
Signed-off-by: Logan McAnsh <[email protected]>
  • Loading branch information
mcansh committed May 25, 2022
1 parent f5a5e15 commit f8855c9
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
21 changes: 19 additions & 2 deletions packages/fetch/src/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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';
}
Expand Down
15 changes: 15 additions & 0 deletions packages/fetch/test/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down

0 comments on commit f8855c9

Please sign in to comment.