eslint-plugin-unicorn
eslint-plugin-unicorn copied to clipboard
Rule proposal: force `method: "POST"` on fetch calls with body
Description
I sometimes forget to add method: 'POST' to fetch calls
Fail
fetch('http://example.com', { body: '{}' })
Pass
fetch('http://example.com', { method: 'POST', body: '{}' })
Additional Info
No response
Another thing related to fetch - disallow specifying method: 'GET' as it will be set by default
Should not enforce POST, but forbid 'GET'(or omitted)/'HEAD'
No HTTP method strictly forbids a body, and there are definitely examples of APIs that accept a body on GET, like elasticsearch.
No HTTP method strictly forbids a body
The fetch spec forbid it,
If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is
GETorHEAD, then throw a TypeError.
https://fetch.spec.whatwg.org/#request-class
Interesting, didn't know that. I guess some implemententations may opt to not implement that step, but for a general case, it seems good to have the rule for it then.
I do forsee that the spec may change in the future, similar to how initially a body on DELETE was forbidden by older RFCs, but newer specs now say it MAY have a body 😉. At least OpenAPI reverted their previous policy and they do allow body on GET,HEAD and DELETE.
no-invalid-fetch-options?
no-invalid-fetch-options
👍