Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd819f93

Browse files
committed
feat: add Response.json static method
Signed-off-by: Logan McAnsh <logan@mcan.sh>
1 parentf5a5e15 commitd819f93

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

‎packages/fetch/src/response.js

Lines changed: 19 additions & 2 deletions
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
exportdefaultclassResponseextendsBody{
@@ -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+
staticjson(data,responseInit={}){
135+
letheaders=newHeaders(responseInit.headers);
136+
if(!headers.has("Content-Type")){
137+
headers.set("Content-Type","application/json; charset=utf-8");
138+
}
139+
140+
returnnewResponse(JSON.stringify(data),{
141+
...responseInit,
142+
headers,
143+
});
144+
}
145+
129146
get[Symbol.toStringTag](){
130147
return'Response';
131148
}

‎packages/fetch/test/response.js

Lines changed: 16 additions & 0 deletions
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
importTestServerfrom'./utils/server.js';
77
import{ReadableStream}from'../src/package.js';
8+
importexpfrom'constants';
89

910
const{expect}=chai;
1011

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

203219
conststreamFromString=text=>newReadableStream({

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp