tachybase_todo/packages/app/src/api-client.ts

82 lines
2.4 KiB
TypeScript
Raw Normal View History

2020-12-11 15:09:39 +08:00
import { stringify } from 'querystring';
import { request } from 'umi';
interface ActionParams {
resourceKey?: string | number;
// resourceName?: string;
// associatedName?: string;
associatedKey?: string | number;
fields?: any;
filter?: any;
values?: any;
page?: any;
perPage?: any;
[key: string]: any;
}
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>;
}
class ApiClient {
resource(name: string): Resource {
const proxy: any = new Proxy({}, {
get(target, method, receiver) {
return (params: ActionParams = {}) => {
2020-12-12 16:32:18 +08:00
let { associatedKey, resourceKey, filter, sorter, sort = [], ...restParams } = params;
let url = `/${name}`;
2020-12-12 16:32:18 +08:00
sort = sort || [];
2020-12-11 15:09:39 +08:00
let options: any = {
params: {},
};
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}`;
}
2020-12-11 15:09:39 +08:00
if (filter) {
options.params['filter'] = JSON.stringify(filter);
}
2020-12-12 16:32:18 +08:00
if (sorter) {
const arr = Array.isArray(sorter) ? sorter : [sorter];
arr.forEach(({order, field}) => {
if (order === 'descend') {
sort.push(`-${field}`);
} else if (order === 'ascend') {
sort.push(field);
}
});
}
if (sort.length === 0) {
delete options.params['sort'];
} else {
options.params['sort'] = sort.join(',');
}
console.log({url, params});
return request(url, options);
};
}
});
return proxy;
}
}
const api = new ApiClient();
export default api;