@yeepay/client-utils 1.2.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,9 +1,10 @@
1
- # 易宝支付 client utils
1
+ # 易宝支付 大前端 client utils
2
+
3
+ [![npm](https://img.shields.io/npm/v/@yeepay/client-utils?color=444&label=)](https://npmjs.com/package/@yeepay/client-utils)
2
4
 
3
5
  - **getQueryObject**: 获取 url 参数
4
- - **setTokenFromUrl(key)**: 通过 url 中的参数 key 设置 TOKEN, 并存入 cookie 中
6
+ - **setTokenFromUrl(key)**: 通过 url 中的参数 key 设置 TOKEN, 并存入 cookie 中
5
7
  - **getToken**: 从 cookie 中获取 TOKEN
6
8
  - **removeToken**: 从 cookie 中删除 TOKEN
7
9
  - **serviceFactory**: 请求封装的工厂函数
8
10
  - **GraphQLClient**: graphql 客户端实现类
9
-
@@ -0,0 +1,31 @@
1
+ import * as axios from 'axios';
2
+ import { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
3
+
4
+ declare function getQueryObject(url: string): Record<string, string>;
5
+
6
+ interface ServiceFactoryOptions {
7
+ baseUrl?: string;
8
+ timeout?: number;
9
+ headers?: Record<string, string>;
10
+ code?: string | number;
11
+ }
12
+ interface ServiceFactoryCallbacks {
13
+ successCallback: (response: AxiosResponse<any>) => any;
14
+ failCallback: (error: any) => any;
15
+ unauthorizedCallback: (response: AxiosResponse<any>) => any;
16
+ forbiddenCallback: (response: AxiosResponse<any> | any) => any;
17
+ notfoundCallback: (response: AxiosResponse<any> | any) => any;
18
+ requestInterceptor: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig;
19
+ responseInterceptor: (response: AxiosResponse<any>) => AxiosResponse<any>;
20
+ }
21
+ type ServiceFactoryCallbacksCompatible = [ServiceFactoryCallbacks['failCallback']?, ServiceFactoryCallbacks['unauthorizedCallback']?, ServiceFactoryCallbacks['forbiddenCallback']?, ServiceFactoryCallbacks['notfoundCallback']?, ServiceFactoryCallbacks['requestInterceptor']?, ServiceFactoryCallbacks['responseInterceptor']?];
22
+ declare function serviceFactory(options: ServiceFactoryOptions, callbacks: ServiceFactoryCallbacks['successCallback'], ...compatibleCallbacks: ServiceFactoryCallbacksCompatible): axios.AxiosInstance;
23
+
24
+ declare function getToken(): string | undefined;
25
+ /**
26
+ * method set token from url.
27
+ */
28
+ declare function setTokenFromUrl(key: string): void;
29
+ declare function removeToken(): void;
30
+
31
+ export { getQueryObject, getToken, removeToken, serviceFactory, setTokenFromUrl };
@@ -0,0 +1,31 @@
1
+ import * as axios from 'axios';
2
+ import { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
3
+
4
+ declare function getQueryObject(url: string): Record<string, string>;
5
+
6
+ interface ServiceFactoryOptions {
7
+ baseUrl?: string;
8
+ timeout?: number;
9
+ headers?: Record<string, string>;
10
+ code?: string | number;
11
+ }
12
+ interface ServiceFactoryCallbacks {
13
+ successCallback: (response: AxiosResponse<any>) => any;
14
+ failCallback: (error: any) => any;
15
+ unauthorizedCallback: (response: AxiosResponse<any>) => any;
16
+ forbiddenCallback: (response: AxiosResponse<any> | any) => any;
17
+ notfoundCallback: (response: AxiosResponse<any> | any) => any;
18
+ requestInterceptor: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig;
19
+ responseInterceptor: (response: AxiosResponse<any>) => AxiosResponse<any>;
20
+ }
21
+ type ServiceFactoryCallbacksCompatible = [ServiceFactoryCallbacks['failCallback']?, ServiceFactoryCallbacks['unauthorizedCallback']?, ServiceFactoryCallbacks['forbiddenCallback']?, ServiceFactoryCallbacks['notfoundCallback']?, ServiceFactoryCallbacks['requestInterceptor']?, ServiceFactoryCallbacks['responseInterceptor']?];
22
+ declare function serviceFactory(options: ServiceFactoryOptions, callbacks: ServiceFactoryCallbacks['successCallback'], ...compatibleCallbacks: ServiceFactoryCallbacksCompatible): axios.AxiosInstance;
23
+
24
+ declare function getToken(): string | undefined;
25
+ /**
26
+ * method set token from url.
27
+ */
28
+ declare function setTokenFromUrl(key: string): void;
29
+ declare function removeToken(): void;
30
+
31
+ export { getQueryObject, getToken, removeToken, serviceFactory, setTokenFromUrl };
package/dist/index.js ADDED
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ getQueryObject: () => getQueryObject,
34
+ getToken: () => getToken,
35
+ removeToken: () => removeToken,
36
+ serviceFactory: () => serviceFactory,
37
+ setTokenFromUrl: () => setTokenFromUrl
38
+ });
39
+ module.exports = __toCommonJS(src_exports);
40
+
41
+ // src/utils.ts
42
+ function getQueryObject(url) {
43
+ url = url == null ? window.location.href : url;
44
+ const search = url.substring(url.lastIndexOf("?") + 1);
45
+ const obj = {};
46
+ const reg = /([^?&=]+)=([^?&=]*)/g;
47
+ search.replace(reg, (rs, $1, $2) => {
48
+ const name = decodeURIComponent($1);
49
+ let val = decodeURIComponent($2);
50
+ val = String(val);
51
+ obj[name] = val;
52
+ return rs;
53
+ });
54
+ return obj;
55
+ }
56
+
57
+ // src/request/index.ts
58
+ var import_axios = __toESM(require("axios"));
59
+ var import_utils2 = require("@imyangyong/utils");
60
+
61
+ // src/request/token.ts
62
+ var import_js_cookie = __toESM(require("js-cookie"));
63
+ var TokenKey = "TOKEN";
64
+ var urlToken = "";
65
+ function getToken() {
66
+ return urlToken || import_js_cookie.default.get(TokenKey);
67
+ }
68
+ function setTokenFromUrl(key) {
69
+ urlToken = getQueryObject(window.location.href)[key];
70
+ if (urlToken) {
71
+ const hashIndex = urlToken.indexOf("#");
72
+ if (hashIndex !== -1)
73
+ urlToken = urlToken.slice(0, hashIndex);
74
+ urlToken = `Bearer ${urlToken}`;
75
+ import_js_cookie.default.set(TokenKey, urlToken);
76
+ const reg = new RegExp(`(${key}=[^&]+&?)`);
77
+ window.history.replaceState(
78
+ null,
79
+ "",
80
+ window.location.href.replace(reg, (_matched) => "")
81
+ );
82
+ }
83
+ }
84
+ function removeToken() {
85
+ return import_js_cookie.default.remove(TokenKey);
86
+ }
87
+
88
+ // src/request/index.ts
89
+ function verifySuccessCode(code, customCode) {
90
+ if (customCode)
91
+ return (0, import_utils2.toArray)(customCode).includes(code) || !code;
92
+ return code === 0 || code === "0" || code === "000000" || code === 200 || !code;
93
+ }
94
+ function compatibleCallback(callbacks, compatibleCallbacks) {
95
+ if (typeof callbacks === "function" || !callbacks) {
96
+ return {
97
+ successCallback: callbacks || (() => ({})),
98
+ failCallback: compatibleCallbacks[0] || (() => ({})),
99
+ unauthorizedCallback: compatibleCallbacks[1] || (() => ({})),
100
+ forbiddenCallback: compatibleCallbacks[2] || (() => ({})),
101
+ notfoundCallback: compatibleCallbacks[3] || (() => ({})),
102
+ requestInterceptor: compatibleCallbacks[4] || ((c) => c),
103
+ responseInterceptor: compatibleCallbacks[5] || ((r) => r)
104
+ };
105
+ } else {
106
+ return callbacks;
107
+ }
108
+ }
109
+ function serviceFactory(options, callbacks, ...compatibleCallbacks) {
110
+ const {
111
+ baseUrl = "/",
112
+ timeout = 12e5,
113
+ // 默认 2 分钟
114
+ headers,
115
+ code
116
+ } = options;
117
+ const {
118
+ successCallback = (_response) => ({}),
119
+ failCallback = (_error) => ({}),
120
+ unauthorizedCallback = (_response) => ({}),
121
+ forbiddenCallback = (_response) => ({}),
122
+ notfoundCallback = (_response) => ({}),
123
+ requestInterceptor = (c) => c,
124
+ responseInterceptor = (r) => r
125
+ } = compatibleCallback(callbacks, compatibleCallbacks);
126
+ const service = import_axios.default.create({
127
+ baseURL: baseUrl,
128
+ timeout,
129
+ // 请求超时时间
130
+ headers,
131
+ validateStatus(status) {
132
+ return status >= 200 && status < 300 || status === 401 || status === 403 || status === 400 || status === 500;
133
+ }
134
+ });
135
+ service.interceptors.request.use(requestInterceptor, (error) => {
136
+ console.log(error);
137
+ void Promise.reject(error);
138
+ });
139
+ service.interceptors.request.use(
140
+ (config) => {
141
+ config.headers.Authorization = getToken();
142
+ const { method, url = "" } = config;
143
+ if (method === "get") {
144
+ if (url.includes("?"))
145
+ config.url = `${url}&_t=${(/* @__PURE__ */ new Date()).getTime()}`;
146
+ else
147
+ config.url = `${url}?_t=${(/* @__PURE__ */ new Date()).getTime()}`;
148
+ }
149
+ return config;
150
+ },
151
+ (error) => {
152
+ console.log(error);
153
+ void Promise.reject(error);
154
+ }
155
+ );
156
+ service.interceptors.response.use(
157
+ (response) => {
158
+ if (response.status && response.status === 401)
159
+ return unauthorizedCallback(response);
160
+ if (response.status && response.status === 403)
161
+ return forbiddenCallback(response);
162
+ if (response.status && (response.status === 400 || response.status === 500)) {
163
+ failCallback(response);
164
+ return Promise.reject(response);
165
+ }
166
+ if (verifySuccessCode(response.data.code, code)) {
167
+ successCallback(response);
168
+ return response;
169
+ } else {
170
+ failCallback(response);
171
+ return Promise.reject(response);
172
+ }
173
+ },
174
+ (error) => {
175
+ let status = 0;
176
+ try {
177
+ status = error.response.status || error.response.data.status;
178
+ } catch (e) {
179
+ if (error.toString().includes("Error: timeout"))
180
+ return Promise.reject(error);
181
+ }
182
+ if (status) {
183
+ if (status === 403)
184
+ forbiddenCallback(error);
185
+ else if (status === 404)
186
+ notfoundCallback(error);
187
+ else
188
+ failCallback(error.response);
189
+ } else {
190
+ failCallback(error.response);
191
+ }
192
+ return Promise.reject(error);
193
+ }
194
+ );
195
+ service.interceptors.response.use(responseInterceptor, (error) => {
196
+ return Promise.reject(error);
197
+ });
198
+ return service;
199
+ }
200
+ // Annotate the CommonJS export names for ESM import in node:
201
+ 0 && (module.exports = {
202
+ getQueryObject,
203
+ getToken,
204
+ removeToken,
205
+ serviceFactory,
206
+ setTokenFromUrl
207
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,166 @@
1
+ // src/utils.ts
2
+ function getQueryObject(url) {
3
+ url = url == null ? window.location.href : url;
4
+ const search = url.substring(url.lastIndexOf("?") + 1);
5
+ const obj = {};
6
+ const reg = /([^?&=]+)=([^?&=]*)/g;
7
+ search.replace(reg, (rs, $1, $2) => {
8
+ const name = decodeURIComponent($1);
9
+ let val = decodeURIComponent($2);
10
+ val = String(val);
11
+ obj[name] = val;
12
+ return rs;
13
+ });
14
+ return obj;
15
+ }
16
+
17
+ // src/request/index.ts
18
+ import axios from "axios";
19
+ import { toArray } from "@imyangyong/utils";
20
+
21
+ // src/request/token.ts
22
+ import Cookie from "js-cookie";
23
+ var TokenKey = "TOKEN";
24
+ var urlToken = "";
25
+ function getToken() {
26
+ return urlToken || Cookie.get(TokenKey);
27
+ }
28
+ function setTokenFromUrl(key) {
29
+ urlToken = getQueryObject(window.location.href)[key];
30
+ if (urlToken) {
31
+ const hashIndex = urlToken.indexOf("#");
32
+ if (hashIndex !== -1)
33
+ urlToken = urlToken.slice(0, hashIndex);
34
+ urlToken = `Bearer ${urlToken}`;
35
+ Cookie.set(TokenKey, urlToken);
36
+ const reg = new RegExp(`(${key}=[^&]+&?)`);
37
+ window.history.replaceState(
38
+ null,
39
+ "",
40
+ window.location.href.replace(reg, (_matched) => "")
41
+ );
42
+ }
43
+ }
44
+ function removeToken() {
45
+ return Cookie.remove(TokenKey);
46
+ }
47
+
48
+ // src/request/index.ts
49
+ function verifySuccessCode(code, customCode) {
50
+ if (customCode)
51
+ return toArray(customCode).includes(code) || !code;
52
+ return code === 0 || code === "0" || code === "000000" || code === 200 || !code;
53
+ }
54
+ function compatibleCallback(callbacks, compatibleCallbacks) {
55
+ if (typeof callbacks === "function" || !callbacks) {
56
+ return {
57
+ successCallback: callbacks || (() => ({})),
58
+ failCallback: compatibleCallbacks[0] || (() => ({})),
59
+ unauthorizedCallback: compatibleCallbacks[1] || (() => ({})),
60
+ forbiddenCallback: compatibleCallbacks[2] || (() => ({})),
61
+ notfoundCallback: compatibleCallbacks[3] || (() => ({})),
62
+ requestInterceptor: compatibleCallbacks[4] || ((c) => c),
63
+ responseInterceptor: compatibleCallbacks[5] || ((r) => r)
64
+ };
65
+ } else {
66
+ return callbacks;
67
+ }
68
+ }
69
+ function serviceFactory(options, callbacks, ...compatibleCallbacks) {
70
+ const {
71
+ baseUrl = "/",
72
+ timeout = 12e5,
73
+ // 默认 2 分钟
74
+ headers,
75
+ code
76
+ } = options;
77
+ const {
78
+ successCallback = (_response) => ({}),
79
+ failCallback = (_error) => ({}),
80
+ unauthorizedCallback = (_response) => ({}),
81
+ forbiddenCallback = (_response) => ({}),
82
+ notfoundCallback = (_response) => ({}),
83
+ requestInterceptor = (c) => c,
84
+ responseInterceptor = (r) => r
85
+ } = compatibleCallback(callbacks, compatibleCallbacks);
86
+ const service = axios.create({
87
+ baseURL: baseUrl,
88
+ timeout,
89
+ // 请求超时时间
90
+ headers,
91
+ validateStatus(status) {
92
+ return status >= 200 && status < 300 || status === 401 || status === 403 || status === 400 || status === 500;
93
+ }
94
+ });
95
+ service.interceptors.request.use(requestInterceptor, (error) => {
96
+ console.log(error);
97
+ void Promise.reject(error);
98
+ });
99
+ service.interceptors.request.use(
100
+ (config) => {
101
+ config.headers.Authorization = getToken();
102
+ const { method, url = "" } = config;
103
+ if (method === "get") {
104
+ if (url.includes("?"))
105
+ config.url = `${url}&_t=${(/* @__PURE__ */ new Date()).getTime()}`;
106
+ else
107
+ config.url = `${url}?_t=${(/* @__PURE__ */ new Date()).getTime()}`;
108
+ }
109
+ return config;
110
+ },
111
+ (error) => {
112
+ console.log(error);
113
+ void Promise.reject(error);
114
+ }
115
+ );
116
+ service.interceptors.response.use(
117
+ (response) => {
118
+ if (response.status && response.status === 401)
119
+ return unauthorizedCallback(response);
120
+ if (response.status && response.status === 403)
121
+ return forbiddenCallback(response);
122
+ if (response.status && (response.status === 400 || response.status === 500)) {
123
+ failCallback(response);
124
+ return Promise.reject(response);
125
+ }
126
+ if (verifySuccessCode(response.data.code, code)) {
127
+ successCallback(response);
128
+ return response;
129
+ } else {
130
+ failCallback(response);
131
+ return Promise.reject(response);
132
+ }
133
+ },
134
+ (error) => {
135
+ let status = 0;
136
+ try {
137
+ status = error.response.status || error.response.data.status;
138
+ } catch (e) {
139
+ if (error.toString().includes("Error: timeout"))
140
+ return Promise.reject(error);
141
+ }
142
+ if (status) {
143
+ if (status === 403)
144
+ forbiddenCallback(error);
145
+ else if (status === 404)
146
+ notfoundCallback(error);
147
+ else
148
+ failCallback(error.response);
149
+ } else {
150
+ failCallback(error.response);
151
+ }
152
+ return Promise.reject(error);
153
+ }
154
+ );
155
+ service.interceptors.response.use(responseInterceptor, (error) => {
156
+ return Promise.reject(error);
157
+ });
158
+ return service;
159
+ }
160
+ export {
161
+ getQueryObject,
162
+ getToken,
163
+ removeToken,
164
+ serviceFactory,
165
+ setTokenFromUrl
166
+ };
package/package.json CHANGED
@@ -1,46 +1,57 @@
1
1
  {
2
2
  "name": "@yeepay/client-utils",
3
- "version": "1.2.1",
3
+ "version": "2.0.0",
4
+ "packageManager": "pnpm@8.12.1",
4
5
  "description": "shared utilities for yeepay client packages",
5
- "main": "dist/client-utils.min.js",
6
- "module": "dist/client-utils.esm.js",
7
- "types": "types.d.ts",
8
- "global": "YeepayClientUtils",
9
- "scripts": {
10
- "test": "echo \"Error: no test specified\"",
11
- "build": "rollup --config rollup.build.js"
12
- },
13
- "repository": {
14
- "type": "git",
15
- "url": "git+https://github.com/YeePay-UED/client-utils.git"
16
- },
6
+ "author": "Angus Yang",
7
+ "homepage": "http://gitlab.yeepay.com/ued/client-utils#readme",
17
8
  "keywords": [
18
- "yeepay",
19
9
  "utils",
20
10
  "client-utils"
21
11
  ],
22
- "author": "Angus Yang",
23
- "license": "ISC",
24
- "bugs": {
25
- "url": "https://github.com/YeePay-UED/client-utils/issues"
26
- },
27
- "homepage": "https://github.com/YeePay-UED/client-utils#readme",
28
- "devDependencies": {
29
- "@babel/core": "^7.1.2",
30
- "@babel/plugin-proposal-class-properties": "^7.18.6",
31
- "@babel/preset-env": "^7.1.0",
32
- "@rollup/plugin-babel": "^5.2.1",
33
- "@rollup/plugin-commonjs": "^15.1.0",
34
- "@rollup/plugin-json": "^4.1.0",
35
- "@rollup/plugin-node-resolve": "^9.0.0",
36
- "rollup": "^2.30.0",
37
- "rollup-plugin-terser": "^7.0.2"
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/index.js",
15
+ "require": "./dist/index.cjs"
16
+ }
38
17
  },
18
+ "main": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "files": [
21
+ "dist"
22
+ ],
39
23
  "dependencies": {
24
+ "@imyangyong/utils": "^0.4.1",
25
+ "@types/js-cookie": "^3.0.6",
40
26
  "apollo-boost": "^0.4.9",
41
- "axios": "^0.27.2",
27
+ "axios": "^1.6.3",
42
28
  "graphql": "^15.6.0",
43
29
  "js-cookie": "^2.2.1",
44
30
  "unfetch": "^4.2.0"
31
+ },
32
+ "devDependencies": {
33
+ "@antfu/ni": "^0.21.12",
34
+ "@yeepay/eslint-config": "^1.4.0",
35
+ "bumpp": "^9.2.1",
36
+ "eslint-plugin-format": "^0.1.0",
37
+ "simple-git-hooks": "^2.9.0",
38
+ "tsup": "^8.0.1",
39
+ "typescript": "^5.3.3",
40
+ "vitest": "^1.0.4"
41
+ },
42
+ "simple-git-hooks": {
43
+ "pre-commit": "pnpm lint-staged"
44
+ },
45
+ "lint-staged": {
46
+ "*": "eslint --fix"
47
+ },
48
+ "scripts": {
49
+ "build": "tsup --format esm,cjs --clean --dts",
50
+ "stub": "tsup --format esm",
51
+ "dev": "tsup --format esm,cjs --watch",
52
+ "watch": "tsup --format esm,cjs --watch",
53
+ "lint": "eslint .",
54
+ "release": "bumpp && pnpm publish",
55
+ "test": "vitest"
45
56
  }
46
- }
57
+ }
package/.babelrc DELETED
@@ -1,15 +0,0 @@
1
- {
2
- "presets": [
3
- ["@babel/preset-env", {
4
- "modules": false
5
- }]
6
- ],
7
- "plugins": [
8
- [
9
- "@babel/plugin-proposal-class-properties",
10
- {
11
- "loose": true
12
- }
13
- ]
14
- ]
15
- }
@@ -1 +0,0 @@
1
- import t from"axios";import e from"js-cookie";import n from"apollo-boost";import r from"unfetch";function o(t){var e=(t=null==t?window.location.href:t).substring(t.lastIndexOf("?")+1),n={};return e.replace(/([^?&=]+)=([^?&=]*)/g,(function(t,e,r){var o=decodeURIComponent(e),i=decodeURIComponent(r);return i=String(i),n[o]=i,t})),n}var i="";function u(){return i||e.get("TOKEN")}function a(t){if(i=o(window.location.href)[t]){var n=i.indexOf("#");-1!==n&&(i=i.slice(0,n)),i="Bearer "+i,e.set("TOKEN",i);var r=new RegExp("("+t+"=[^&]+&?)");window.history.replaceState(null,null,window.location.href.replace(r,(function(t){return""})))}}function c(){return e.remove("TOKEN")}function s(t,e){return e?t===e||!t:0===t||"0"===t||"000000"===t||200===t||!t}function l(t,e){return"function"!=typeof t&&t?t:{successCallback:t||function(){return{}},failCallback:e[0]||function(){return{}},unauthorizedCallback:e[1]||function(){return{}},forbiddenCallback:e[2]||function(){return{}},notfoundCallback:e[3]||function(){return{}},requestInterceptor:e[4]||function(t){return t},responseInterceptor:e[5]||function(t){return t}}}function f(e,n){for(var r=e.baseUrl,o=void 0===r?"/":r,i=e.timeout,a=void 0===i?12e5:i,c=e.headers,f=e.code,d=arguments.length,p=new Array(d>2?d-2:0),v=2;v<d;v++)p[v-2]=arguments[v];var h=l(n,p),m=h.successCallback,b=void 0===m?function(){return{}}:m,y=h.failCallback,g=void 0===y?function(){return{}}:y,q=h.unauthorizedCallback,w=void 0===q?function(){return{}}:q,C=h.forbiddenCallback,k=void 0===C?function(){return{}}:C,j=h.notfoundCallback,O=void 0===j?function(){return{}}:j,S=h.requestInterceptor,E=void 0===S?function(t){return t}:S,I=h.responseInterceptor,x=void 0===I?function(t){return t}:I,A=t.create({baseURL:o,timeout:a,headers:c,validateStatus:function(t){return t>=200&&t<300||401===t||403===t||400===t||500===t}});return A.interceptors.request.use((function(t){t.headers.Authorization=u(),t.headers["Content-Type"]="application/json";var e=t.method,n=t.url;return"get"===e&&(-1!==n.indexOf("?")?t.url="".concat(n,"&_t=").concat((new Date).getTime()):t.url="".concat(n,"?_t=").concat((new Date).getTime())),t}),(function(t){console.log(t),Promise.reject(t)})),A.interceptors.request.use(E,(function(t){console.log(t),Promise.reject(t)})),A.interceptors.response.use((function(t){return t.status&&401===t.status?w(t):t.status&&403===t.status?k(t):(!t.status||400!==t.status&&500!==t.status)&&s(t.data.code,f)?(b(t),t):(g(t),Promise.reject(t))}),(function(t){var e=0;try{e=t.response.status||t.response.data.status}catch(e){if(-1!==t.toString().indexOf("Error: timeout"))return Promise.reject(t)}return e?403===e?k(t):404===e?O(t):g(t.response):g(t.response),Promise.reject(t)})),A.interceptors.response.use(x,(function(t){})),A}function d(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function p(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var n=[],r=!0,o=!1,i=void 0;try{for(var u,a=t[Symbol.iterator]();!(r=(u=a.next()).done)&&(n.push(u.value),!e||n.length!==e);r=!0);}catch(t){o=!0,i=t}finally{try{r||null==a.return||a.return()}finally{if(o)throw i}}return n}(t,e)||function(t,e){if(!t)return;if("string"==typeof t)return v(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return v(t,e)}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function v(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var h=function(){function t(e){var o=this,i=e.gqlServer,u=e.requestForRest;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.gql={},this.inject=function(t,e){o.register(t);for(var n=function(){var e=p(i[r],2),n=e[0],u=e[1];if(!["definitions","kind","loc"].includes(n))if("query"===u.definitions[0].operation)"production"===process.env.NODE_ENV?o.gql[t][n]=function(e){return o.restfulReq("/".concat(t,"/").concat(n),e)}:o.gql[t][n]=function(t){return o.query(u,t)};else{if("mutation"!==u.definitions[0].operation)return"continue";"production"===process.env.NODE_ENV?o.gql[t][n]=function(e){return o.restfulReq("/".concat(t,"/").concat(n),e)}:o.gql[t][n]=function(t){return o.mutation(u,t)}}},r=0,i=Object.entries(e);r<i.length;r++)n()},this.gqlServer=i,this.request=u,this.apolloClient=new n({uri:i,fetch:r})}var e,o,i;return e=t,(o=[{key:"register",value:function(t){this.gql[t]||(this.gql[t]={})}},{key:"query",value:function(t,e){return this.apolloClient.query({query:t,variables:e||{}})}},{key:"mutation",value:function(t,e){return this.apolloClient.mutate({mutation:t,variables:e||{}})}},{key:"restfulReq",value:function(t,e){return this.request({url:t,method:"post",data:{variables:e}})}}])&&d(e.prototype,o),i&&d(e,i),t}();export{h as GraphQLClient,o as getQueryObject,u as getToken,c as removeToken,f as serviceFactory,a as setTokenFromUrl};
@@ -1 +0,0 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("axios"),require("js-cookie"),require("apollo-boost"),require("unfetch")):"function"==typeof define&&define.amd?define(["exports","axios","js-cookie","apollo-boost","unfetch"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).YeepayClientUtils={},e.axios,e.Cookie,e.ApolloClient,e.fetch)}(this,(function(e,t,n,r,o){"use strict";function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=i(t),a=i(n),c=i(r),s=i(o);function l(e){var t=(e=null==e?window.location.href:e).substring(e.lastIndexOf("?")+1),n={};return t.replace(/([^?&=]+)=([^?&=]*)/g,(function(e,t,r){var o=decodeURIComponent(t),i=decodeURIComponent(r);return i=String(i),n[o]=i,e})),n}var f="TOKEN",d="";function p(){return d||a.default.get(f)}function v(e,t){return t?e===t||!e:0===e||"0"===e||"000000"===e||200===e||!e}function h(e,t){return"function"!=typeof e&&e?e:{successCallback:e||function(){return{}},failCallback:t[0]||function(){return{}},unauthorizedCallback:t[1]||function(){return{}},forbiddenCallback:t[2]||function(){return{}},notfoundCallback:t[3]||function(){return{}},requestInterceptor:t[4]||function(e){return e},responseInterceptor:t[5]||function(e){return e}}}function y(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function b(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var n=[],r=!0,o=!1,i=void 0;try{for(var u,a=e[Symbol.iterator]();!(r=(u=a.next()).done)&&(n.push(u.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{r||null==a.return||a.return()}finally{if(o)throw i}}return n}(e,t)||function(e,t){if(!e)return;if("string"==typeof e)return m(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return m(e,t)}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function m(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var g=function(){function e(t){var n=this,r=t.gqlServer,o=t.requestForRest;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.gql={},this.inject=function(e,t){n.register(e);for(var r=function(){var t=b(i[o],2),r=t[0],u=t[1];if(!["definitions","kind","loc"].includes(r))if("query"===u.definitions[0].operation)"production"===process.env.NODE_ENV?n.gql[e][r]=function(t){return n.restfulReq("/".concat(e,"/").concat(r),t)}:n.gql[e][r]=function(e){return n.query(u,e)};else{if("mutation"!==u.definitions[0].operation)return"continue";"production"===process.env.NODE_ENV?n.gql[e][r]=function(t){return n.restfulReq("/".concat(e,"/").concat(r),t)}:n.gql[e][r]=function(e){return n.mutation(u,e)}}},o=0,i=Object.entries(t);o<i.length;o++)r()},this.gqlServer=r,this.request=o,this.apolloClient=new c.default({uri:r,fetch:s.default})}var t,n,r;return t=e,(n=[{key:"register",value:function(e){this.gql[e]||(this.gql[e]={})}},{key:"query",value:function(e,t){return this.apolloClient.query({query:e,variables:t||{}})}},{key:"mutation",value:function(e,t){return this.apolloClient.mutate({mutation:e,variables:t||{}})}},{key:"restfulReq",value:function(e,t){return this.request({url:e,method:"post",data:{variables:t}})}}])&&y(t.prototype,n),r&&y(t,r),e}();e.GraphQLClient=g,e.getQueryObject=l,e.getToken=p,e.removeToken=function(){return a.default.remove(f)},e.serviceFactory=function(e,t){for(var n=e.baseUrl,r=void 0===n?"/":n,o=e.timeout,i=void 0===o?12e5:o,a=e.headers,c=e.code,s=arguments.length,l=new Array(s>2?s-2:0),f=2;f<s;f++)l[f-2]=arguments[f];var d=h(t,l),y=d.successCallback,b=void 0===y?function(){return{}}:y,m=d.failCallback,g=void 0===m?function(){return{}}:m,q=d.unauthorizedCallback,k=void 0===q?function(){return{}}:q,C=d.forbiddenCallback,w=void 0===C?function(){return{}}:C,j=d.notfoundCallback,O=void 0===j?function(){return{}}:j,x=d.requestInterceptor,S=void 0===x?function(e){return e}:x,T=d.responseInterceptor,I=void 0===T?function(e){return e}:T,A=u.default.create({baseURL:r,timeout:i,headers:a,validateStatus:function(e){return e>=200&&e<300||401===e||403===e||400===e||500===e}});return A.interceptors.request.use((function(e){e.headers.Authorization=p(),e.headers["Content-Type"]="application/json";var t=e.method,n=e.url;return"get"===t&&(-1!==n.indexOf("?")?e.url="".concat(n,"&_t=").concat((new Date).getTime()):e.url="".concat(n,"?_t=").concat((new Date).getTime())),e}),(function(e){console.log(e),Promise.reject(e)})),A.interceptors.request.use(S,(function(e){console.log(e),Promise.reject(e)})),A.interceptors.response.use((function(e){return e.status&&401===e.status?k(e):e.status&&403===e.status?w(e):(!e.status||400!==e.status&&500!==e.status)&&v(e.data.code,c)?(b(e),e):(g(e),Promise.reject(e))}),(function(e){var t=0;try{t=e.response.status||e.response.data.status}catch(t){if(-1!==e.toString().indexOf("Error: timeout"))return Promise.reject(e)}return t?403===t?w(e):404===t?O(e):g(e.response):g(e.response),Promise.reject(e)})),A.interceptors.response.use(I,(function(e){})),A},e.setTokenFromUrl=function(e){if(d=l(window.location.href)[e]){var t=d.indexOf("#");-1!==t&&(d=d.slice(0,t)),d="Bearer "+d,a.default.set(f,d);var n=new RegExp("("+e+"=[^&]+&?)");window.history.replaceState(null,null,window.location.href.replace(n,(function(e){return""})))}},Object.defineProperty(e,"__esModule",{value:!0})}));
package/index.js DELETED
@@ -1,20 +0,0 @@
1
- /* common */
2
- import { getQueryObject } from './lib/common'
3
-
4
- /* request */
5
- import { serviceFactory } from './lib/request'
6
-
7
- /* graphql */
8
- import GraphQLClient from './lib/graphql'
9
-
10
- /* token */
11
- import { setTokenFromUrl, getToken, removeToken } from './lib/token';
12
-
13
- export {
14
- getQueryObject,
15
- serviceFactory,
16
- GraphQLClient,
17
- setTokenFromUrl,
18
- getToken,
19
- removeToken
20
- }
package/lib/common.js DELETED
@@ -1,19 +0,0 @@
1
- /**
2
- * 获取 url 参数
3
- * @param {string} url
4
- * @returns {Object}
5
- */
6
- export function getQueryObject(url) {
7
- url = url == null ? window.location.href : url
8
- const search = url.substring(url.lastIndexOf('?') + 1)
9
- const obj = {}
10
- const reg = /([^?&=]+)=([^?&=]*)/g
11
- search.replace(reg, (rs, $1, $2) => {
12
- const name = decodeURIComponent($1)
13
- let val = decodeURIComponent($2)
14
- val = String(val)
15
- obj[name] = val
16
- return rs
17
- })
18
- return obj
19
- }
package/lib/graphql.js DELETED
@@ -1,103 +0,0 @@
1
- import ApolloClient from 'apollo-boost'
2
- import fetch from 'unfetch';
3
-
4
- /**
5
- * method Instantiate a graphql apollo client.
6
- * @param {String} gqlServer gql server address.
7
- * @return {Object} return graphql apollo client.
8
- */
9
- export default class GraphQLClient {
10
- constructor({ gqlServer, requestForRest }) {
11
- this.gqlServer = gqlServer
12
- this.request = requestForRest
13
-
14
- // 创建ApolloClient实例
15
- this.apolloClient = new ApolloClient({
16
- uri: gqlServer,
17
- fetch: fetch
18
- })
19
- }
20
-
21
- /* 存储多模块 graphql */
22
- gql = {}
23
-
24
- /**
25
- * method register module.
26
- * @param {String} module.
27
- */
28
- register(module) {
29
- if (!this.gql[module]) {
30
- this.gql[module] = {}
31
- }
32
- }
33
-
34
- /**
35
- * method graphql query.
36
- * @param {String} graphql.
37
- * @param {Object} params.
38
- * @return {Promise} return promise response.
39
- */
40
- query(graphql, params) {
41
- return this.apolloClient.query({
42
- query: graphql,
43
- variables: params || {}
44
- })
45
- }
46
-
47
- /**
48
- * method graphql mutation.
49
- * @param {String} graphql.
50
- * @param {Object} params.
51
- * @return {Promise} return promise response.
52
- */
53
- mutation(graphql, params) {
54
- return this.apolloClient.mutate({
55
- mutation: graphql,
56
- variables: params || {}
57
- })
58
- }
59
-
60
- /**
61
- * method traditional restful api.
62
- * @param {String} url.
63
- * @param {Object} data Variables.
64
- * @return {Promise}.
65
- */
66
- restfulReq(url, data) {
67
- return this.request({
68
- url,
69
- method: 'post',
70
- data: {
71
- variables: data
72
- }
73
- })
74
- }
75
-
76
- /**
77
- * method inject the graphqls into a module.
78
- * @param {Object} module The module name that will be inject the graphql.
79
- * @param {Object} sources Graphql.
80
- */
81
- inject = (module, sources) => {
82
- this.register(module)
83
- for (const [key, value] of Object.entries(sources)) {
84
- if (!['definitions', 'kind', 'loc'].includes(key)) {
85
- if (value.definitions[0].operation === 'query') {
86
- if (process.env.NODE_ENV === 'production') {
87
- this.gql[module][key] = (params) => this.restfulReq(`/${module}/${key}`, params)
88
- } else {
89
- this.gql[module][key] = (params) => this.query(value, params)
90
- }
91
- } else if (value.definitions[0].operation === 'mutation') {
92
- if (process.env.NODE_ENV === 'production') {
93
- this.gql[module][key] = (params) => this.restfulReq(`/${module}/${key}`, params)
94
- } else {
95
- this.gql[module][key] = (params) => this.mutation(value, params)
96
- }
97
- } else {
98
- continue
99
- }
100
- }
101
- }
102
- }
103
- }
package/lib/request.js DELETED
@@ -1,166 +0,0 @@
1
- import axios from 'axios'
2
- import { getToken } from './token'
3
-
4
- function verifySuccessCode(code, customCode) {
5
- if (customCode) {
6
- return code === customCode || !code
7
- }
8
-
9
- return code === 0 ||
10
- code === '0' ||
11
- code === '000000' ||
12
- code === 200 ||
13
- !code
14
- }
15
-
16
- function compatibleCallback(callbacks, compatibleCallbacks) {
17
- if (typeof callbacks === 'function' || !callbacks) {
18
- return {
19
- successCallback: callbacks || (() => ({})),
20
- failCallback: compatibleCallbacks[0] || (() => ({})),
21
- unauthorizedCallback: compatibleCallbacks[1] || (() => ({})),
22
- forbiddenCallback: compatibleCallbacks[2] || (() => ({})),
23
- notfoundCallback: compatibleCallbacks[3] || (() => ({})),
24
- requestInterceptor: compatibleCallbacks[4] || ((c) => (c)),
25
- responseInterceptor: compatibleCallbacks[5] || ((r) => (r))
26
- }
27
- } else {
28
- return callbacks
29
- }
30
- }
31
-
32
- /**
33
- * method service factory.
34
- * @param {Object} options baseUrl/timeout/headers<object>.
35
- * @param {Function} successCallback.
36
- * @param {Function} failCallback.
37
- * @param {Function} unauthorizedCallback.
38
- * @param {Function} forbiddenCallback.
39
- * @param {Function} notfoundCallback.
40
- * @return {Function} return axios instance.
41
- */
42
- export function serviceFactory(
43
- options,
44
- callbacks,
45
- ...compatibleCallbacks
46
- ) {
47
- const {
48
- baseUrl = '/',
49
- timeout = 1200000, // 默认 2 分钟
50
- headers,
51
- code,
52
- } = options
53
-
54
- const {
55
- successCallback = () => ({}),
56
- failCallback = () => ({}),
57
- unauthorizedCallback = () => ({}),
58
- forbiddenCallback = () => ({}),
59
- notfoundCallback = () => ({}),
60
- requestInterceptor = (c) => (c),
61
- responseInterceptor = (r) => (r)
62
- } = compatibleCallback(callbacks, compatibleCallbacks)
63
-
64
- // 创建axios实例
65
- const service = axios.create({
66
- baseURL: baseUrl,
67
- timeout, // 请求超时时间
68
- headers,
69
- validateStatus: function (status) {
70
- // 401, 403 在拦截器中 resolve 处理, 由于可能需要其报文
71
- return (
72
- (status >= 200 && status < 300) ||
73
- status === 401 ||
74
- status === 403 ||
75
- status === 400 ||
76
- status === 500
77
- )
78
- }
79
- })
80
-
81
- // request拦截器
82
- service.interceptors.request.use(
83
- (config) => {
84
- config.headers['Authorization'] = getToken()
85
- config.headers['Content-Type'] = 'application/json'
86
- const { method, url } = config
87
- if (method === 'get') {
88
- if (url.indexOf('?') !== -1) {
89
- config.url = `${url}&_t=${new Date().getTime()}`
90
- } else {
91
- config.url = `${url}?_t=${new Date().getTime()}`
92
- }
93
- }
94
- return config
95
- },
96
- (error) => {
97
- // Do something with request error
98
- console.log(error) // for debug
99
- Promise.reject(error)
100
- }
101
- )
102
-
103
- service.interceptors.request.use(requestInterceptor,
104
- (error) => {
105
- // Do something with request error
106
- console.log(error) // for debug
107
- Promise.reject(error)
108
- })
109
-
110
- // response 拦截器
111
- service.interceptors.response.use(
112
- (response) => {
113
- // 401, 403 返回报文
114
- if (response.status && response.status === 401) {
115
- return unauthorizedCallback(response)
116
- }
117
-
118
- if (response.status && response.status === 403) {
119
- return forbiddenCallback(response)
120
- }
121
- // 400, 500 返回报文
122
- if (
123
- response.status &&
124
- (response.status === 400 || response.status === 500)
125
- ) {
126
- failCallback(response)
127
- return Promise.reject(response)
128
- }
129
- // !response.data.code, code为假 那么可能为文件流
130
- if (verifySuccessCode(response.data.code, code)) {
131
- successCallback(response)
132
- return response
133
- } else {
134
- failCallback(response)
135
- return Promise.reject(response)
136
- }
137
- },
138
- (error) => {
139
- let status = 0
140
- try {
141
- status = error.response.status || error.response.data.status
142
- } catch (e) {
143
- if (error.toString().indexOf('Error: timeout') !== -1) {
144
- return Promise.reject(error)
145
- }
146
- }
147
-
148
- if (status) {
149
- if (status === 403) {
150
- forbiddenCallback(error)
151
- } else if (status === 404) {
152
- notfoundCallback(error)
153
- } else {
154
- failCallback(error.response)
155
- }
156
- } else {
157
- failCallback(error.response)
158
- }
159
- return Promise.reject(error)
160
- }
161
- )
162
-
163
- service.interceptors.response.use(responseInterceptor,
164
- (error) => { })
165
- return service
166
- }
package/lib/token.js DELETED
@@ -1,37 +0,0 @@
1
- import Cookie from 'js-cookie'
2
- import { getQueryObject } from './common'
3
-
4
- let TokenKey = 'TOKEN'
5
- let urlToken = ''
6
-
7
- export function getToken() {
8
- return urlToken || Cookie.get(TokenKey)
9
- }
10
-
11
- /**
12
- * method set token from url.
13
- * @param {String} key Token key.
14
- */
15
- export function setTokenFromUrl(key) {
16
- // url has token ?
17
- urlToken = getQueryObject(window.location.href)[key]
18
- if (urlToken) {
19
- const hashIndex = urlToken.indexOf('#')
20
- if (hashIndex !== -1) {
21
- urlToken = urlToken.slice(0, hashIndex)
22
- }
23
- urlToken = 'Bearer ' + urlToken
24
- Cookie.set(TokenKey, urlToken)
25
-
26
- const reg = new RegExp('(' + key + '=[^&]+&?)')
27
- window.history.replaceState(
28
- null,
29
- null,
30
- window.location.href.replace(reg, (matched) => '')
31
- )
32
- }
33
- }
34
-
35
- export function removeToken() {
36
- return Cookie.remove(TokenKey)
37
- }
package/rollup.build.js DELETED
@@ -1,38 +0,0 @@
1
- import { terser } from 'rollup-plugin-terser'
2
- import json from '@rollup/plugin-json'
3
- import { nodeResolve } from '@rollup/plugin-node-resolve'
4
- import commonjs from '@rollup/plugin-commonjs'
5
- import { babel } from '@rollup/plugin-babel'
6
- const config = require('./package.json');
7
-
8
- const source = {
9
- input: './index.js',
10
- external: [ 'axios' ],
11
- plugins: [
12
- // nodeResolve(), // 将第三方模块注入我们的 bundle 中
13
- // commonjs(), // 将 CommonJS 模块转换为 ES6 module, node-resolve 与 commonjs 需配合使用
14
- babel({ exclude: 'node_modules/**', babelHelpers: 'bundled' }),
15
- json(),
16
- terser()
17
- ]
18
- }
19
-
20
- const umd = {
21
- file: config.main,
22
- format: 'umd',
23
- name: config.global,
24
- exports: 'named',
25
- }
26
-
27
- const esm = {
28
- file: config.module,
29
- format: 'esm',
30
- }
31
-
32
- export default {
33
- ...source,
34
- output: [
35
- umd,
36
- esm
37
- ]
38
- }