UNPKG

@wordpress/api-fetch

Version:
83 lines (78 loc) 2.32 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseAndThrowError = parseAndThrowError; exports.parseResponseAndNormalizeError = void 0; var _i18n = require("@wordpress/i18n"); /** * WordPress dependencies */ /** * Parses the apiFetch response. * * @param {Response} response * @param {boolean} shouldParseResponse * * @return {Promise<any> | null | Response} Parsed response. */ const parseResponse = (response, shouldParseResponse = true) => { if (shouldParseResponse) { if (response.status === 204) { return null; } return response.json ? response.json() : Promise.reject(response); } return response; }; /** * Calls the `json` function on the Response, throwing an error if the response * doesn't have a json function or if parsing the json itself fails. * * @param {Response} response * @return {Promise<any>} Parsed response. */ const parseJsonAndNormalizeError = response => { const invalidJsonError = { code: 'invalid_json', message: (0, _i18n.__)('The response is not a valid JSON response.') }; if (!response || !response.json) { throw invalidJsonError; } return response.json().catch(() => { throw invalidJsonError; }); }; /** * Parses the apiFetch response properly and normalize response errors. * * @param {Response} response * @param {boolean} shouldParseResponse * * @return {Promise<any>} Parsed response. */ const parseResponseAndNormalizeError = (response, shouldParseResponse = true) => { return Promise.resolve(parseResponse(response, shouldParseResponse)).catch(res => parseAndThrowError(res, shouldParseResponse)); }; /** * Parses a response, throwing an error if parsing the response fails. * * @param {Response} response * @param {boolean} shouldParseResponse * @return {Promise<any>} Parsed response. */ exports.parseResponseAndNormalizeError = parseResponseAndNormalizeError; function parseAndThrowError(response, shouldParseResponse = true) { if (!shouldParseResponse) { throw response; } return parseJsonAndNormalizeError(response).then(error => { const unknownError = { code: 'unknown_error', message: (0, _i18n.__)('An unknown error occurred.') }; throw error || unknownError; }); } //# sourceMappingURL=response.js.map