@amanooo/fetch
Version:
custom fetch
121 lines (120 loc) • 5.01 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("./util");
const fetchImport = require("isomorphic-unfetch");
const fetch = (fetchImport.default || fetchImport);
var Color;
(function (Color) {
// blue = 'color:blue',
// red = 'color:red'
Color["blue"] = "";
Color["red"] = "";
})(Color || (Color = {}));
class Fetch {
static get(url, params = {}, options = {}, retryOpts = {}) {
return __awaiter(this, void 0, void 0, function* () {
const completeUrl = url + util_1.obj2urlParams(params);
const _options = Object.assign({ headers: Object.assign({}, this.headers, { 'content-type': 'text/plain' }), credentials: this.credentials }, options);
const result = yield this.fetch(completeUrl, _options, retryOpts);
return result;
});
}
static post(url, body = {}, options = {}, retryOpts = {}) {
return __awaiter(this, void 0, void 0, function* () {
this.debug && console.debug('__post__:', url);
const _options = Object.assign({ method: 'POST', body: JSON.stringify(body), headers: this.headers, credentials: this.credentials }, options);
const result = yield this.fetch(url, _options, retryOpts);
return result;
});
}
static put(url, body = {}, options = {}, retryOpts = {}) {
return __awaiter(this, void 0, void 0, function* () {
const _options = Object.assign({ method: 'PUT', body: JSON.stringify(body), headers: this.headers, credentials: this.credentials }, options);
const result = yield this.fetch(url, _options, retryOpts);
return result;
});
}
static delete(url, body = {}, options = {}, retryOpts = {}) {
return __awaiter(this, void 0, void 0, function* () {
const _options = Object.assign({ method: 'DELETE', body: JSON.stringify(body), headers: this.headers, credentials: this.credentials }, options);
const result = yield this.fetch(url, _options, retryOpts);
return result;
});
}
static fetch(url, options, retryOpts = {}) {
return __awaiter(this, void 0, void 0, function* () {
const start = new Date();
const mark = `__${(options.method || 'GET').toLowerCase()}__`;
this.debug && console.debug('%s: %s, options', mark, url, options);
const _retryOpts = Object.assign({}, util_1.commonRetryOpts(), this.retryOpts, retryOpts);
const action = (_) => {
return fetch(url, options)
.then(util_1.filter200Status)
.catch((e) => {
console.error('%s %s:%s Error Cost %f ms', Color.red, mark, url, util_1.cost(start), e);
throw e;
});
};
const result = yield retry(action, _retryOpts);
this.debug && console.debug('%s %s: %s Success Cost %f ms res: %o', Color.blue, mark, url, util_1.cost(start), result);
return result;
});
}
}
Fetch.headers = util_1.commonHeaders();
Fetch.credentials = "same-origin";
Fetch.debug = false;
Fetch.retryOpts = util_1.commonRetryOpts();
exports.default = Fetch;
function bail(err) {
throw (err || new Error('Aborted'));
}
function retry(action, options) {
return __awaiter(this, void 0, void 0, function* () {
const { retries, timeout: _timeout, delay: _dealy } = options;
function doAction() {
return Promise.race([util_1.timeout(_timeout), action()]);
}
let times = 1;
let response;
while (times <= retries) {
try {
response = yield doAction();
break;
}
catch (error) {
if (times >= retries) {
throw new Error(error);
}
yield util_1.delay(_dealy);
}
finally {
times++;
}
}
return response;
});
}
class ResultUtil {
static send(error, payload) {
return {
error,
payload
};
}
static success(payload) {
return ResultUtil.send(null, payload);
}
static fail(error = 'DEFAULT ERROR') {
return ResultUtil.send(error);
}
}
exports.ResultUtil = ResultUtil;