| 19 | import apiDefinitions from './apiDefinitions'; |
| 20 | |
| 21 | const createFunctionalProxy = (array, alovaInstance, configMap) => { |
| 22 | // create a new proxy instance |
| 23 | return new Proxy(function () {}, { |
| 24 | get(_, property) { |
| 25 | // record the target property, so that it can get the completed accessing paths |
| 26 | array.push(property); |
| 27 | // always return a new proxy to continue recording accessing paths. |
| 28 | return createFunctionalProxy(array, alovaInstance, configMap); |
| 29 | }, |
| 30 | apply(_, __, [data, config]) { |
| 31 | const apiItem = apiDefinitions[array.join('.')]; |
| 32 | if (!apiItem) { |
| 33 | throw new Error(`the api path of \`${apiItem}\` is not found`); |
| 34 | } |
| 35 | const [method, url] = apiItem; |
| 36 | const urlReplaced = url.replace(/\{([^}]+)\}/g, (_, key) => { |
| 37 | const pathParam = data[key]; |
| 38 | delete data[key]; |
| 39 | return pathParam; |
| 40 | }); |
| 41 | // correct the params when request with different type |
| 42 | if (/^POST|PUT|DELETE|PATCH$/i.test(method)) { |
| 43 | config.params = data; |
| 44 | data = undefined; |
| 45 | } |
| 46 | return new Method(method.toUpperCase(), alovaInstance, urlReplaced, config, data); |
| 47 | } |
| 48 | }); |
| 49 | }; |
| 50 | |
| 51 | export const createApis = (alovaInstance, configMap) => |
| 52 | new Proxy( |