UNPKG

1.5 kBJavaScriptView Raw
1import { RequestError } from './errors.js';
2export const isResponseOk = (response) => {
3 const { statusCode } = response;
4 const { followRedirect } = response.request.options;
5 const shouldFollow = typeof followRedirect === 'function' ? followRedirect(response) : followRedirect;
6 const limitStatusCode = shouldFollow ? 299 : 399;
7 return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304;
8};
9/**
10An error to be thrown when server response code is 2xx, and parsing body fails.
11Includes a `response` property.
12*/
13export class ParseError extends RequestError {
14 constructor(error, response) {
15 const { options } = response.request;
16 super(`${error.message} in "${options.url.toString()}"`, error, response.request);
17 this.name = 'ParseError';
18 this.code = 'ERR_BODY_PARSE_FAILURE';
19 }
20}
21export const parseBody = (response, responseType, parseJson, encoding) => {
22 const { rawBody } = response;
23 try {
24 if (responseType === 'text') {
25 return rawBody.toString(encoding);
26 }
27 if (responseType === 'json') {
28 return rawBody.length === 0 ? '' : parseJson(rawBody.toString(encoding));
29 }
30 if (responseType === 'buffer') {
31 return rawBody;
32 }
33 }
34 catch (error) {
35 throw new ParseError(error, response);
36 }
37 throw new ParseError({
38 message: `Unknown body type '${responseType}'`,
39 name: 'Error',
40 }, response);
41};