UNPKG

2.42 kBJavaScriptView Raw
1import axios from "axios";
2
3class Apis {
4 constructor(serverMap, apiMap) {
5 this.serverMap = serverMap;
6 this.apiMap = apiMap;
7 this.instance = {
8 gRequest: axios.request
9 };
10
11 if (this.validate) {
12 this.format();
13 this.middleware();
14 this.combine();
15 return this.instance;
16 } else {
17 console.error("apis: 参数不合法,请检查你的配置参数");
18 }
19 }
20
21 get validate() {
22 return true;
23 }
24
25 get base() {
26 let base = "";
27
28 for (const key of Object.keys(this.serverMap)) {
29 if (!base) {
30 base = key;
31 }
32
33 if (this.serverMap[key].default) {
34 base = key;
35 }
36 }
37
38 if (!base) {
39 console.error("apis: 找不到默认服务器配置");
40 }
41
42 return base;
43 }
44
45 format() {
46 for (const key of Object.keys(this.apiMap)) {
47 const item = this.apiMap[key];
48
49 if (!item.server) {
50 item.server = this.base;
51 }
52
53 this.apiMap[key] = Object.assign({}, this.serverMap[item.server], item);
54 }
55 }
56
57 middleware() {
58 Apis.reqMiddleware.map(function(middleware) {
59 axios.interceptors.request.use(...middleware);
60 });
61
62 Apis.resMiddleware.map(function(middleware) {
63 axios.interceptors.response.use(...middleware);
64 });
65 }
66
67 restful(url, rest) {
68 const regex = /\:[^/]*/g;
69
70 return url.replace(regex, p => {
71 const key = p.slice(1);
72 if (rest[key]) {
73 return rest[key];
74 }
75 return p;
76 });
77 }
78
79 comboo(bf, af) {
80 if (af.rest) {
81 af.url = this.restful(bf.url, af.rest);
82 }
83
84 return Object.assign({}, bf, af);
85 }
86
87 namespace(obj, keys, cb) {
88 const key = keys[0];
89
90 if (keys.length === 1) {
91 obj[key] = obj[key] || cb;
92 } else {
93 obj[key] = obj[key] || {};
94 this.namespace(obj[key], keys.slice(1), cb);
95 }
96 }
97
98 combine() {
99 for (const key of Object.keys(this.apiMap)) {
100 const keys = key.replace(/^\//, "").split("/");
101 this.namespace(this.instance, keys, config => {
102 let result = this.apiMap[key];
103 if (config) {
104 result = this.comboo(this.apiMap[key], config);
105 }
106 return axios.request(result);
107 });
108 }
109 }
110}
111
112Apis.reqMiddleware = [];
113Apis.resMiddleware = [];
114
115Apis.useReq = function() {
116 Apis.reqMiddleware.push(arguments);
117};
118Apis.useRes = function() {
119 Apis.resMiddleware.push(arguments);
120};
121
122export default Apis;