Skip to content

Commit d819f93

Browse files
committed
feat: add Response.json static method
Signed-off-by: Logan McAnsh <[email protected]>
1 parent f5a5e15 commit d819f93

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

packages/fetch/src/response.js

+19-2
Original file line numberDiff line numberDiff 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
*/
2424
export 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
}

packages/fetch/test/response.js

+16
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {Blob} from '@remix-run/web-blob';
55
import {Response} from '@remix-run/web-fetch';
66
import TestServer from './utils/server.js';
77
import { ReadableStream } from '../src/package.js';
8+
import exp from 'constants';
89

910
const {expect} = chai;
1011

@@ -198,6 +199,21 @@ describe('Response', () => {
198199
const res = new Response();
199200
expect(res.url).to.equal('');
200201
});
202+
203+
it('should support json static method', () => {
204+
const res = Response.json({a: 1});
205+
return res.json().then(result => {
206+
expect(result.a).to.equal(1);
207+
});
208+
})
209+
210+
it('should support json static method with added responseInit', () => {
211+
const res = Response.json({a: 1}, { headers: { "x-foo": "bar" } });
212+
expect(res.headers.get('x-foo')).to.equal('bar');
213+
return res.json().then(result => {
214+
expect(result.a).to.equal(1);
215+
});
216+
})
201217
});
202218

203219
const streamFromString = text => new ReadableStream({

0 commit comments

Comments
 (0)