@lancercomet/fetcher
Version:
Yet another fetcher.
333 lines (321 loc) • 15.3 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var suntori = require('@lancercomet/suntori');
var qs = require('qs');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var qs__default = /*#__PURE__*/_interopDefaultLegacy(qs);
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(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());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var isFunction = function (target) {
return typeof target === 'function';
};
/**
* Fetcher.
*
* @class Fetcher
*/
var Fetcher = /** @class */ (function () {
function Fetcher(param) {
this._param = undefined;
this._interceptors = [];
this._abortController = new AbortController();
this._param = param;
}
Fetcher.prototype._createParamByInterceptors = function (param) {
var result = param;
for (var _i = 0, _a = this._interceptors.filter(function (item) { return isFunction(item); }); _i < _a.length; _i++) {
var func = _a[_i];
result = func(result);
}
return result;
};
/**
* Abort requesting.
*/
Fetcher.prototype.abort = function () {
var _a;
(_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort();
};
/**
* Add a function to intercept the request.
*
* @param {Interceptor} func The interceptor function.
* @returns {() => void} The function to remove the interceptor.
*/
Fetcher.prototype.setInterceptor = function (func) {
var _this = this;
if (!this._interceptors.includes(func)) {
this._interceptors.push(func);
}
return function () {
var index = _this._interceptors.indexOf(func);
if (index > -1) {
_this._interceptors.splice(index, 1);
}
};
};
Fetcher.prototype._request = function (param) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
return __awaiter(this, void 0, void 0, function () {
var url, method, data, headers, isGet, isFormData, queryString, baseUrl, timeout, timeoutTimer, response, error_1;
var _this = this;
return __generator(this, function (_m) {
switch (_m.label) {
case 0:
param = this._createParamByInterceptors(param);
url = (_a = param.url) !== null && _a !== void 0 ? _a : '';
method = param.method;
data = (_b = param.data) !== null && _b !== void 0 ? _b : {};
headers = {};
isGet = method === 'GET';
isFormData = data instanceof FormData;
if (method === 'GET') {
queryString = qs__default["default"].stringify(data);
if (queryString) {
url += '?' + queryString;
}
}
else if (!isFormData) {
headers['Content-Type'] = 'application/json';
}
Object.assign(headers, (_d = (_c = param.options) === null || _c === void 0 ? void 0 : _c.headers) !== null && _d !== void 0 ? _d : {});
baseUrl = (_e = this._param) === null || _e === void 0 ? void 0 : _e.baseUrl;
if (baseUrl) {
url = baseUrl + url;
}
this._abortController = new AbortController();
timeout = (_g = (_f = this._param) === null || _f === void 0 ? void 0 : _f.timeout) !== null && _g !== void 0 ? _g : -1;
timeoutTimer = null;
if (timeout > -1) {
timeoutTimer = setTimeout(function () { return _this.abort(); }, timeout);
}
_m.label = 1;
case 1:
_m.trys.push([1, 3, , 4]);
return [4 /*yield*/, fetch(url, {
method: method,
headers: headers,
cache: (_h = param.options) === null || _h === void 0 ? void 0 : _h.cache,
credentials: (_j = param.options) === null || _j === void 0 ? void 0 : _j.credentials,
redirect: (_k = param.options) === null || _k === void 0 ? void 0 : _k.redirect,
referrerPolicy: (_l = param.options) === null || _l === void 0 ? void 0 : _l.referrerPolicy,
signal: this._abortController.signal,
body: isGet
? undefined
: isFormData
? data
: JSON.stringify(data)
})];
case 2:
response = _m.sent();
clearTimeout(timeoutTimer);
return [2 /*return*/, response];
case 3:
error_1 = _m.sent();
clearTimeout(timeoutTimer);
throw error_1;
case 4: return [2 /*return*/];
}
});
});
};
/**
* Send Http request and read the response as JSON.
*
* @template T
* @param {IFetcherRequestParam<T>} param
*/
Fetcher.prototype.requestJSON = function (param) {
return __awaiter(this, void 0, void 0, function () {
var result, response, json, type_1, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
result = {
data: undefined,
error: undefined,
status: 0
};
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 5]);
return [4 /*yield*/, this._request(param)];
case 2:
response = _a.sent();
result.status = response.status;
if (response.status >= 400) {
throw new Error("Http ".concat(status));
}
return [4 /*yield*/, response.json()];
case 3:
json = _a.sent();
type_1 = param.type;
if (!type_1) {
result.data = json;
}
else {
if (Array.isArray(json)) {
result.data = json.map(function (item) { return suntori.deserialize(item, type_1); });
}
else {
result.data = suntori.deserialize(json, type_1);
}
}
return [3 /*break*/, 5];
case 4:
error_2 = _a.sent();
result.error = error_2;
return [3 /*break*/, 5];
case 5: return [2 /*return*/, result];
}
});
});
};
/**
* Send http request and read the response as "The API".
*
* @param param
*/
Fetcher.prototype.requestAPI = function (param) {
return __awaiter(this, void 0, void 0, function () {
var result, response, apiResponse, type_2, data, error_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
result = {
data: undefined,
error: undefined,
status: 0,
code: 0,
message: ''
};
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 5]);
return [4 /*yield*/, this._request(param)];
case 2:
response = _a.sent();
result.status = response.status;
if (response.status >= 400) {
throw new Error("Http ".concat(status));
}
return [4 /*yield*/, response.json()];
case 3:
apiResponse = _a.sent();
result.code = apiResponse.code;
result.message = apiResponse.message;
type_2 = param.type;
data = apiResponse.data;
if (!type_2) {
result.data = data;
}
else {
if (Array.isArray(data)) {
result.data = data.map(function (item) { return suntori.deserialize(item, type_2); });
}
else {
result.data = suntori.deserialize(data, type_2);
}
}
return [3 /*break*/, 5];
case 4:
error_3 = _a.sent();
result.error = error_3;
return [3 /*break*/, 5];
case 5: return [2 /*return*/, result];
}
});
});
};
Fetcher.prototype.requestBinary = function (param, type) {
return __awaiter(this, void 0, void 0, function () {
var result, response, _a, _b, error_4;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
result = {
data: undefined,
error: undefined,
status: 0
};
_c.label = 1;
case 1:
_c.trys.push([1, 7, , 8]);
return [4 /*yield*/, this._request(param)];
case 2:
response = _c.sent();
result.status = response.status;
if (response.status >= 400) {
throw new Error("Http ".concat(status));
}
if (!(type === 'arraybuffer')) return [3 /*break*/, 4];
_a = result;
return [4 /*yield*/, response.arrayBuffer()];
case 3:
_a.data = _c.sent();
return [3 /*break*/, 6];
case 4:
_b = result;
return [4 /*yield*/, response.blob()];
case 5:
_b.data = _c.sent();
_c.label = 6;
case 6: return [3 /*break*/, 8];
case 7:
error_4 = _c.sent();
result.error = error_4;
return [3 /*break*/, 8];
case 8: return [2 /*return*/, result];
}
});
});
};
return Fetcher;
}());
exports.Fetcher = Fetcher;