Skip to content
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

httpApiCall behavior with 2xx codes. #234

Open
sashapop10 opened this issue Dec 15, 2023 · 0 comments
Open

httpApiCall behavior with 2xx codes. #234

sashapop10 opened this issue Dec 15, 2023 · 0 comments
Labels
bug Something isn't working

Comments

@sashapop10
Copy link

sashapop10 commented Dec 15, 2023

Describe the bug

In case if someone will response with 201(Created), 202(Accepted) or other 2xx status codes - httpApiCall will throw an Error. More than that, in the source code i found that httpApiCall mutates headers parameter and even doesn't use it afterwards.

const httpApiCall = async (url, { method = 'POST', headers = {}, body }) => {
  const mimeType = 'application/json';
  const custom = { 'Content-Type': mimeType, ...headers };
  if (body) headers['Content-Length'] = Buffer.byteLength(body); // Useless code
  // Should be replaced by: if (body) custom['Content-Length'] = Buffer.byteLength(body);
  const options = { method, headers: custom, body };
  return await fetch(url, options).then(async (res) => {
    const code = res.status;
    if (code === 200) return await res.json(); // Is that normal behavior to ignore other 2xx codes?
    const dest = `for ${method} ${url}`;
    throw new Error(`HTTP status code ${code} ${dest}`);
  });
};

Additional context

I think next realization will fix this issue.
This realization also allows to provide more fetch options.

const DEFAULT_METHOD = 'POST';
const DEFAULT_MIME = 'application/json';
const httpApiCall = (url, { headers = {}, ...options }) => {
  const body = options.body;
  options.headers = { 'Content-Type': DEFAULT_MIME, ...headers };
  options.method ??= DEFAULT_METHOD;
  if (body) options.headers['Content-Length'] = Buffer.byteLength(body);
  return fetch(url, options).then(res => {
    if (res.status >= 200 && res.status < 300) return res.json();
    throw new Error(`HTTP status code ${res.status} for ${method} ${url}`);
  });
};
@sashapop10 sashapop10 added the bug Something isn't working label Dec 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant