2020-11-13 22:01:14 +08:00
|
|
|
import { request } from 'umi';
|
|
|
|
|
2020-12-01 20:11:39 +08:00
|
|
|
interface ActionParams {
|
2020-11-13 22:01:14 +08:00
|
|
|
resourceKey?: string | number;
|
|
|
|
// resourceName?: string;
|
|
|
|
// associatedName?: string;
|
|
|
|
associatedKey?: string | number;
|
|
|
|
fields?: any;
|
|
|
|
filter?: any;
|
2020-12-01 20:11:39 +08:00
|
|
|
values?: any;
|
|
|
|
page?: any;
|
|
|
|
perPage?: any;
|
2020-11-21 23:49:59 +08:00
|
|
|
[key: string]: any;
|
2020-11-13 22:01:14 +08:00
|
|
|
}
|
|
|
|
|
2020-12-01 20:11:39 +08:00
|
|
|
interface Resource {
|
|
|
|
get: (params?: ActionParams) => Promise<any>;
|
|
|
|
list: (params?: ActionParams) => Promise<any>;
|
|
|
|
create: (params?: ActionParams) => Promise<any>;
|
|
|
|
update: (params?: ActionParams) => Promise<any>;
|
|
|
|
destroy: (params?: ActionParams) => Promise<any>;
|
|
|
|
[name: string]: (params?: ActionParams) => Promise<any>;
|
2020-11-13 22:01:14 +08:00
|
|
|
}
|
|
|
|
|
2020-12-01 20:11:39 +08:00
|
|
|
class ApiClient {
|
|
|
|
resource(name: string): Resource {
|
|
|
|
const proxy: any = new Proxy({}, {
|
2020-11-13 22:01:14 +08:00
|
|
|
get(target, method, receiver) {
|
2020-12-01 20:11:39 +08:00
|
|
|
return (params: ActionParams = {}) => {
|
2020-11-13 22:01:14 +08:00
|
|
|
const { associatedKey, resourceKey, ...restParams } = params;
|
|
|
|
let url = `/${name}`;
|
|
|
|
let options: any = {};
|
|
|
|
if (['list', 'get'].indexOf(method as string) !== -1) {
|
|
|
|
options.method = 'get';
|
|
|
|
options.params = restParams;
|
|
|
|
} else {
|
|
|
|
options.method = 'post';
|
|
|
|
options.data = restParams;
|
|
|
|
}
|
|
|
|
if (associatedKey) {
|
|
|
|
url = `/${name.split('.').join(`/${associatedKey}/`)}`;
|
|
|
|
}
|
|
|
|
url += `:${method as string}`;
|
|
|
|
// console.log(name, name.split('.'), associatedKey, name.split('.').join(`/${associatedKey}/`));
|
|
|
|
if (resourceKey) {
|
|
|
|
url += `/${resourceKey}`;
|
|
|
|
}
|
|
|
|
console.log({url, params});
|
|
|
|
return request(url, options);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
});
|
2020-12-01 20:11:39 +08:00
|
|
|
return proxy;
|
2020-11-13 22:01:14 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-01 20:11:39 +08:00
|
|
|
const api = new ApiClient();
|
2020-11-13 22:01:14 +08:00
|
|
|
|
|
|
|
export default api;
|