UNPKG

@ferry-core/ferry

Version:

common fetch tool for ferry service

199 lines (192 loc) 9.09 kB
/*! * @ferry-core/ferry with v0.1.2 * Author: yanpan * Built on 2023-09-03, 23:14:37 * Released under the MIT License Copyright (c) 2023 */ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var oar=require('@ferry-core/oar');/****************************************************************************** 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. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol */ function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } 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()); }); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; };// import buildURL from './utils/getUrl'; const defaultFailMsg = 'Request fail'; const defaultErrorMsg = 'Network error or server crush'; const defaultErrorCode = null; class Ferry { constructor(options) { // extend baseUrl this.baseURL = ''; // customize header this.headers = {}; this.oarClient = oar.create(options); } static getInstance(options) { if (!this.ferryInstance) { this.ferryInstance = new Ferry(options); } return this.ferryInstance; } apiOar(_a) { var { baseURL = this.baseURL, headers = this.headers, method, url, data, params, responseType, customCodes = [0] } = _a, others = __rest(_a, ["baseURL", "headers", "method", "url", "data", "params", "responseType", "customCodes"]); // url transform // const formUrl = buildURL(url, params); const oarClientConfig = Object.assign({ baseURL, headers, method, url, params, data, responseType }, others); return new Promise((resolve, reject) => { this.oarClient(oarClientConfig) .then((res) => { var _a, _b, _c, _d, _e, _f, _g, _h; const resObj = Object.assign(Object.assign({}, res), { statusCode: res.status, code: (_a = res.data) === null || _a === void 0 ? void 0 : _a.code, data: (_b = res.data) === null || _b === void 0 ? void 0 : _b.data, msg: ((_c = res.data) === null || _c === void 0 ? void 0 : _c.msg) || ((_d = res.data) === null || _d === void 0 ? void 0 : _d.message), ttl: (_e = res.data) === null || _e === void 0 ? void 0 : _e.ttl, origin: res.data, config: res.config }); // 200: success from backend process 204: success too if ([200, 201, 204].includes(res === null || res === void 0 ? void 0 : res.status)) { const code = (_f = res.data) === null || _f === void 0 ? void 0 : _f.code; const cusCodeList = Array.isArray(customCodes) ? customCodes : [+customCodes]; if (code == null || !cusCodeList.includes(code)) { // code is null or undefined, then default as false resolve(Object.assign(Object.assign({}, resObj), { status: false, msg: resObj.msg || ((_g = res.data) === null || _g === void 0 ? void 0 : _g.errorMessage) || defaultFailMsg, type: 'fail' })); } else { // code is not null or undefined,means meanful response resolve(Object.assign(Object.assign({}, resObj), { status: true, type: 'success' })); } } else { resolve(Object.assign(Object.assign({}, resObj), { status: false, msg: resObj.msg || ((_h = res.data) === null || _h === void 0 ? void 0 : _h.errorMessage) || defaultFailMsg, type: 'fail' })); } }) .catch((err) => { var _a; const { status: errResStatus, config, data = null, code = defaultErrorCode, } = err.response; const msg = ((_a = err === null || err === void 0 ? void 0 : err.data) === null || _a === void 0 ? void 0 : _a.errorMessage) || (err === null || err === void 0 ? void 0 : err.msg) || (err === null || err === void 0 ? void 0 : err.message) || defaultErrorMsg; // eslint-disable-next-line reject(Object.assign(Object.assign({}, err), { error: err, status: false, statusCode: errResStatus, code, config: config || oarClientConfig, msg, data, type: 'error' })); }); }); } /** * Get Ferry's oar instance,Ferry is singleton,so oarClient is singleton too */ oarInstance() { return this.oarClient; } /** * GET */ getReq(props) { return this.apiOar(Object.assign(Object.assign({}, props), { method: 'GET' })); } /** * POST */ postReq(props) { return this.apiOar(Object.assign(Object.assign({}, props), { method: 'POST' })); } /** * PUT */ putReq(props) { return this.apiOar(Object.assign(Object.assign({}, props), { method: 'PUT' })); } /** * DELETE */ deleteReq(props) { return this.apiOar(Object.assign(Object.assign({}, props), { method: 'DELETE' })); } } // default config,timeout equals 10s,response type: json const defaultConfig = { timeout: 10000, responseType: 'json', }; // Ferry singleton instance const ferryClient = Ferry.getInstance(defaultConfig);const fetchWrapper = (fn, target, errorHandler = console.log) => (...params) => __awaiter(void 0, void 0, void 0, function* () { try { const res = yield fn.apply(target, params); return res; } catch (error) { errorHandler(error); } });// get protocol function ferryGet(props) { return fetchWrapper(ferryClient.getReq, ferryClient, props === null || props === void 0 ? void 0 : props.errorHandler)(props); } // post protocol function ferryPst(props) { return fetchWrapper(ferryClient.postReq, ferryClient, props === null || props === void 0 ? void 0 : props.errorHandler)(props); } // put protocol function ferryPut(props) { return fetchWrapper(ferryClient.putReq, ferryClient, props === null || props === void 0 ? void 0 : props.errorHandler)(props); } // delete protocol function ferryDel(props) { return fetchWrapper(ferryClient.deleteReq, ferryClient, props === null || props === void 0 ? void 0 : props.errorHandler)(props); } const ferry = ferryClient.oarInstance(); const win = typeof window !== 'undefined' ? window : undefined; win && (win.injectInfo = (win.injectInfo || {})); win && win.injectInfo && !win.injectInfo.ferryGet && (win.injectInfo.ferryGet = ferryGet); win && win.injectInfo && !win.injectInfo.ferryPst && (win.injectInfo.ferryPst = ferryPst); win && win.injectInfo && !win.injectInfo.ferryPut && (win.injectInfo.ferryPut = ferryPut); win && win.injectInfo && !win.injectInfo.ferryDel && (win.injectInfo.ferryDel = ferryDel); win && win.injectInfo && !win.injectInfo.ferry && (win.injectInfo.ferry = ferryClient);exports.default=ferry;exports.ferry=ferry;exports.ferryDel=ferryDel;exports.ferryGet=ferryGet;exports.ferryPst=ferryPst;exports.ferryPut=ferryPut;//# sourceMappingURL=ferry.cjs.map