-
-
Notifications
You must be signed in to change notification settings - Fork 360
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Rule proposal: prefer-static-response-json
instead of new Response(JSON.stringify())
#1960
Comments
The method is quite new, so the rule cannot be in the recommended preset, and we should add a note in the docs about it being quite new. |
This pattern seems rarely used. https://github.com/search?q=new Response(JSON.stringify&type=code&p=1 |
For what purpose are you |
There are two
In my unit tests, I mock the fetch method to return a specific JSON (examples in Cast Kodi): it("should return video URL", async function () {
const stub = sinon.stub(globalThis, "fetch").resolves(new Response(
JSON.stringify({
media: [{
id: "foo",
offline_url: "http://bar.com/baz.mp4",
}],
}),
));
const file = await scraper.extract("https://watch.pokemon.com/player?id=foo");
assert.equal(file, "http://bar.com/baz.mp4");
assert.equal(stub.callCount, 1);
assert.deepEqual(stub.firstCall.args, [
"https://www.pokemon.com/api/pokemontv/v2/channels/uk",
]);
}); With this new rule, the above code would be in error. The code can be simplified to: it("should return video URL", async function () {
const stub = sinon.stub(globalThis, "fetch").resolves(Response.json({
media: [{
id: "foo",
offline_url: "http://bar.com/baz.mp4",
}],
}));
// ...
}); |
I see. Yes I suspected the primary use case for this is mocking. So I'm neutral on this one, don't see it much in demand, thought. |
Deno says: "This addition to the Fetch specification was specifically designed with server side runtimes in mind." Deno 1.22 Release Notes - New For example: import { serve } from "https://deno.land/[email protected]/http/server.ts";
const port = 8080;
const handler = (request) => {
const body = { userAgent: request.headers.get("user-agent") ?? "Unknown" };
// Previously:
// return new Response(JSON.stringify(body), {
// headers: { "content-type": "application/json" },
// });
// Now:
return Response.json(body);
};
await serve(handler, { port }); |
Yeah, for servers that support |
Description
Prefer the static
Response.json()
method instead ofnew Response(JSON.stringify())
.More info:
Response.json
helper whatwg/fetch#1389Response.json
static method whatwg/fetch#1392Fail
Pass
The text was updated successfully, but these errors were encountered: