seamless-cloud
Version:
JavaScript client for Seamless.cloud (web and node)
63 lines • 2.9 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchJSON = void 0;
const deepmerge_1 = __importDefault(require("deepmerge"));
const querystringify_1 = __importDefault(require("querystringify"));
/**
* Generic fetch JSON method that handles errors (non-sucessful response codes)
*/
function fetchJSON(fetchFn, method, url, body, fetchOptions = {}) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
const fetchOptionDefaults = {
mode: 'cors',
method,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'Seamless.cloud NPM Client',
},
};
fetchOptions = (0, deepmerge_1.default)(fetchOptionDefaults, fetchOptions);
fetchOptions.method = method.toUpperCase();
if (body && typeof body === 'object') {
if (fetchOptions.method === 'GET') {
url = `${url}?${querystringify_1.default.stringify(body)}`;
}
else {
fetchOptions.body = JSON.stringify(body);
}
}
const res = yield fetchFn(url, fetchOptions);
const json = yield res.json();
const statusCode = res.status;
// Check response to ensure everything is OK...
if (statusCode >= 400) {
const err = new Error(((_a = json.meta) === null || _a === void 0 ? void 0 : _a.message) || json.error_message || json.message || 'Internal Server Error');
// @ts-ignore
err.json = json;
// @ts-ignore
err.number = ((_b = json.meta) === null || _b === void 0 ? void 0 : _b.statusCode) || statusCode || 400;
if (((_c = json.meta) === null || _c === void 0 ? void 0 : _c.errorType) == 'duplicate') {
// @ts-ignore
err.number = 400;
}
throw err;
}
return json;
});
}
exports.fetchJSON = fetchJSON;
//# sourceMappingURL=fetch.js.map