40 lines
1.3 KiB
Plaintext
40 lines
1.3 KiB
Plaintext
|
import { RequestError } from './errors.js';
|
||
|
export const isResponseOk = (response) => {
|
||
|
const { statusCode } = response;
|
||
|
const limitStatusCode = response.request.options.followRedirect ? 299 : 399;
|
||
|
return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304;
|
||
|
};
|
||
|
/**
|
||
|
An error to be thrown when server response code is 2xx, and parsing body fails.
|
||
|
Includes a `response` property.
|
||
|
*/
|
||
|
export class ParseError extends RequestError {
|
||
|
constructor(error, response) {
|
||
|
const { options } = response.request;
|
||
|
super(`${error.message} in "${options.url.toString()}"`, error, response.request);
|
||
|
this.name = 'ParseError';
|
||
|
this.code = 'ERR_BODY_PARSE_FAILURE';
|
||
|
}
|
||
|
}
|
||
|
export const parseBody = (response, responseType, parseJson, encoding) => {
|
||
|
const { rawBody } = response;
|
||
|
try {
|
||
|
if (responseType === 'text') {
|
||
|
return rawBody.toString(encoding);
|
||
|
}
|
||
|
if (responseType === 'json') {
|
||
|
return rawBody.length === 0 ? '' : parseJson(rawBody.toString(encoding));
|
||
|
}
|
||
|
if (responseType === 'buffer') {
|
||
|
return rawBody;
|
||
|
}
|
||
|
}
|
||
|
catch (error) {
|
||
|
throw new ParseError(error, response);
|
||
|
}
|
||
|
throw new ParseError({
|
||
|
message: `Unknown body type '${responseType}'`,
|
||
|
name: 'Error',
|
||
|
}, response);
|
||
|
};
|