Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/big-hounds-sniff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@remix-run/web-fetch": patch
---

add Response.json static method
28 changes: 25 additions & 3 deletions packages/fetch/src/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,18 @@ const INTERNALS = Symbol('Response internals');

/**
* Response class
*
*
* @typedef {Object} Ext
* @property {number} [size]
* @property {string} [url]
* @property {number} [counter]
* @property {number} [highWaterMark]
*
*
* @typedef {Omit<Response, "json"> & {
* json(): Promise<T>;
* }} TypedResponse
* @template T
*
* @implements {globalThis.Response}
*/
export default class Response extends Body {
Expand Down Expand Up @@ -126,6 +131,24 @@ export default class Response extends Body {
});
}

/**
* @template {unknown} Data
* @param {Data} data The data to be converted into a JSON string.
* @param {ResponseInit} [responseInit] An optional status code for the response (e.g., 302.)
* @returns {TypedResponse<Data>} 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 All @@ -140,4 +163,3 @@ Object.defineProperties(Response.prototype, {
headers: {enumerable: true},
clone: {enumerable: true}
});

15 changes: 15 additions & 0 deletions packages/fetch/test/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,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