UNPKG

sunmao-sdk

Version:

榫卯-开箱即用赋能-sdk

458 lines (386 loc) 18 kB
import "antd/es/message/style"; import _message from "antd/es/message"; var _excluded = ["ok", "status", "statusText"]; function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } import lodash, { isString } from "lodash"; import { CP } from ".."; import qs from "qs"; import * as commonUtils from "../utils/commonUtils"; import { isSkipLog, redirectUrl } from "./api"; var codeMessage = { 200: "请求成功,但数据异常!", 201: "新建或修改数据成功。", 202: "一个请求已经进入后台排队(异步任务)。", 204: "删除数据成功。", 400: "发出的请求有错误,服务器没有进行新建或修改数据的操作。", 401: "用户没有权限(令牌、用户名、密码错误)。", 403: "用户得到授权,但是访问是被禁止的。", 404: "发出的请求针对的是不存在的记录,服务器没有进行操作。", 406: "请求的格式不可得。", 410: "请求的资源被永久删除,且不会再得到的。", 422: "当创建一个对象时,发生一个验证错误。", 500: "服务器发生错误,请检查服务器。", 502: "网关错误。", 503: "服务不可用,服务器暂时过载或维护。", 504: "网关超时。" }; var getMsgInfo = function getMsgInfo(obj) { if (!obj) return ""; for (var key in obj) { if (key.includes("Msg") || key.includes("msg") || key.includes("Message") || key.includes("message")) { return obj[key]; } } return; }; var getDataInfo = function getDataInfo(obj) { if (!obj) return true; return obj.data || obj.model || obj.result || obj.module; }; /** * 异常处理程序 */ var errorHandler = /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(error, resType, okPath) { var json, ret, root, ok, status, statusText, other, statusMsg, data, res, dataType, _args = arguments; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: json = _args.length > 3 && _args[3] !== undefined ? _args[3] : true; if (!(!json && okPath && lodash.get(error, okPath))) { _context.next = 8; break; } ret = {}; // 最外层数据 兼容处理 root = okPath.split(".")[0]; ret[root] = lodash.get(error, root); ret.data = ret[root]; // 精确数据 ret.exactData = lodash.get(error, okPath); return _context.abrupt("return", _objectSpread(_objectSpread({}, error), ret)); case 8: ok = error.ok, status = error.status, statusText = error.statusText, other = _objectWithoutProperties(error, _excluded); statusMsg = statusText || getMsgInfo(other); data = getDataInfo(other); // 符合平台返回 res 数据结构 status & ok if (!(status === 200 && ok || lodash.get(error, CP.getCPInfo().postOk))) { _context.next = 24; break; } if (!json) { _context.next = 17; break; } _context.next = 15; return error.json(); case 15: res = _context.sent; return _context.abrupt("return", errorHandler(res, resType, okPath, false)); case 17: if (!resType) { _context.next = 22; break; } dataType = Object.prototype.toString.call(data); if (!(resType !== dataType)) { _context.next = 22; break; } console.error("\u670D\u52A1\u7AEF\u8FD4\u56DE\u7ED3\u6784\u4E3A".concat(dataType, ",\u4E0E\u76EE\u6807").concat(resType, "\u4E0D\u5339\u914D\uFF01")); return _context.abrupt("return", { sdkErrorMsg: "\u670D\u52A1\u7AEF\u8FD4\u56DE\u7ED3\u6784\u4E3A".concat(dataType, ",\u4E0E\u76EE\u6807").concat(resType, "\u4E0D\u5339\u914D\uFF01") }); case 22: statusMsg && isString(statusMsg) && _message.info(statusMsg); return _context.abrupt("return", _objectSpread(_objectSpread({}, other), {}, { data: data })); case 24: return _context.abrupt("return", { sdkErrorMsg: statusMsg || codeMessage[status] || "数据异常!" }); case 25: case "end": return _context.stop(); } } }, _callee); })); return function errorHandler(_x, _x2, _x3) { return _ref.apply(this, arguments); }; }(); /** * @param {接口信息} url * @param {传参信息} params * @param {请求头信息} props * @param {接受结构} resType 用于业务逻辑,返回数据结构不匹配则为业务异常链路;传值推荐:'[object Object]'、'[object Array]' */ var postNew = /*#__PURE__*/function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(url) { var params, okPath, props, resType, loading, res, _args2 = arguments; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: params = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {}; okPath = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : undefined; props = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : {}; resType = _args2.length > 4 && _args2[4] !== undefined ? _args2[4] : false; loading = _args2.length > 5 ? _args2[5] : undefined; params = getCommonParams(params); _context2.next = 8; return request(url, _objectSpread({ method: "POST", mode: "cors", body: JSON.stringify(params), headers: { "content-type": "application/json;charset=utf-8" } }, props), resType, okPath, loading); case 8: res = _context2.sent; return _context2.abrupt("return", res); case 10: case "end": return _context2.stop(); } } }, _callee2); })); return function postNew(_x4) { return _ref2.apply(this, arguments); }; }(); var getCommonParams = function getCommonParams() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; // // 网关转发处理 // if (commonUtils.isObj(params.params)) { // if (!(params.params.projectId && params.params.appId)) { // // 配置至cookie或许更合 // !params.params.projectId && // (params.params.projectId = CP?.info?.projectId); // !params.params.appId && (params.params.appId = CP?.info?.appId); // params.params.deleteSunmaoParams = true; // } // params.params.user = CP?.info?.user; // 配置至cookie或许更合 // params.params.env = CP?.info?.env; // } else { // if (!(params.projectId && params.appId)) { // // 配置至cookie或许更合 // !params.projectId && (params.projectId = CP?.info?.projectId); // !params.appId && (params.appId = CP?.info?.appId); // params.deleteSunmaoParams = true; // } // params.user = CP?.info?.user; // 配置至cookie或许更合适 // params.env = CP?.info?.env; // } // 网关转发处理 if (commonUtils.isObj(params.params)) { if (!params.params.sunmao_Params) { params.params.sunmao_Params = CP.getSunmaoParams(); } } else { if (!params.sunmao_Params) { params.sunmao_Params = CP.getSunmaoParams(); } } return params; }; var urlGetParams = function urlGetParams(url) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; params = getCommonParams(params); url += (url.indexOf("?") > -1 ? "&" : "?") + Object.keys(params).map(function (key) { var _params$key; var value = (_params$key = params[key]) === null || _params$key === void 0 ? void 0 : _params$key.toString(); if (!value) { return "".concat(key); } else if (key === "sunmao_Params") { return Object.keys(params.sunmao_Params).map(function (key) { var _params$sunmao_Params; var value = (_params$sunmao_Params = params.sunmao_Params[key]) === null || _params$sunmao_Params === void 0 ? void 0 : _params$sunmao_Params.toString(); if (!value) { return "sunmao_Params_".concat(key); } else { return "sunmao_Params_".concat(key, "=").concat(encodeURIComponent(value)); } }).join("&"); } else { return "".concat(key, "=").concat(encodeURIComponent(value)); } }).join("&"); return url; }; /** * @param {接口信息} url * @param {传参信息} params * @param {请求头信息} props * @param {接受结构} resType 用于业务逻辑,返回数据结构不匹配则为业务异常链路 * @param {string} okPath 自定义返回成功路径 */ var getNew = /*#__PURE__*/function () { var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(url) { var params, okPath, props, resType, res, _args3 = arguments; return regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: params = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : {}; okPath = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : undefined; props = _args3.length > 3 && _args3[3] !== undefined ? _args3[3] : {}; resType = _args3.length > 4 && _args3[4] !== undefined ? _args3[4] : false; url = urlGetParams(url, params); _context3.next = 7; return request(url, _objectSpread({ method: "GET", mode: "cors" }, props), resType, okPath); case 7: res = _context3.sent; return _context3.abrupt("return", res); case 9: case "end": return _context3.stop(); } } }, _callee3); })); return function getNew(_x5) { return _ref3.apply(this, arguments); }; }(); var request = /*#__PURE__*/function () { var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(url, data, resType, okPath, loading) { return regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: return _context5.abrupt("return", new Promise( /*#__PURE__*/function () { var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(resolve, reject) { var req; return regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: if (!CP.getSunmaoParams().appId) { console.error("未配置应用的appId,通过CP.init进行配置!"); reject("未配置应用的appId,通过CP.init进行配置!"); } req = false; _context4.prev = 2; commonUtils.log("-----request-----:", data, url); _context4.next = 6; return fetch(url, data); case 6: req = _context4.sent; commonUtils.log("--response--first--:", req, url); _context4.next = 10; return errorHandler(req, resType, okPath); case 10: req = _context4.sent; commonUtils.log("--response--handler--:", req, url); try { if (loading) loading.destroy(); } catch (_unused) {} if (!req.sdkErrorMsg) { _context4.next = 17; break; } throw new Error(req.sdkErrorMsg); case 17: // 兼容处理 resolve(!okPath || "data" === okPath ? _objectSpread({ data: req.data }, req.data) : req); case 18: _context4.next = 25; break; case 20: _context4.prev = 20; _context4.t0 = _context4["catch"](2); try { if (loading) loading.destroy(); } catch (_unused2) {} if (isSkipLog(url)) { CP.error("".concat((_context4.t0 === null || _context4.t0 === void 0 ? void 0 : _context4.t0.message) || (_context4.t0 === null || _context4.t0 === void 0 ? void 0 : _context4.t0.msg) || "请求失败!")); } else { commonUtils.log(url, "".concat((_context4.t0 === null || _context4.t0 === void 0 ? void 0 : _context4.t0.message) || (_context4.t0 === null || _context4.t0 === void 0 ? void 0 : _context4.t0.msg) || "请求失败!")); } reject(); case 25: case "end": return _context4.stop(); } } }, _callee4, null, [[2, 20]]); })); return function (_x11, _x12) { return _ref5.apply(this, arguments); }; }())); case 1: case "end": return _context5.stop(); } } }, _callee5); })); return function request(_x6, _x7, _x8, _x9, _x10) { return _ref4.apply(this, arguments); }; }(); // 获取字典信息 var getDicDetails = function getDicDetails(url) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var okPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var props = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var resType = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; return postNew(redirectUrl, { url: urlGetParams(url, params), method: "GET", type: "http" }, okPath, props, resType); }; /** * 应用级 统一处理请求入参函数 * @param {入参} params * @param {入参过滤函数} filter */ var handleAppParams = function handleAppParams(params, filter) { // 先分隔“,” 入参, // 再去除空 入参 var _params = commonUtils.filterParams(commonUtils.splitParams(_objectSpread(_objectSpread({}, CP.getCPInfo().extParams), params))); try { // 自定义过滤函数 return filter ? filter(_params) : _params; } catch (_unused3) { return _params; } }; export { getNew, postNew, urlGetParams, getDicDetails, handleAppParams };