nocobase/packages/app/src/api-client.ts
Junyi cb8edc7b75
feat: export plugin (#73)
* feat: add data export action in table view

* feat: add data render based on interface type for exporting

* fix: use rewrite action name for permissions

* feat: add support for subTable type field

* add datetime render

* export filter support selectedRowKeys

* docs

Co-authored-by: chenos <chenlinxh@gmail.com>
2021-05-17 11:11:49 +08:00

91 lines
2.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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, options?: any) => Promise<any>;
list: (params?: ActionParams, options?: any) => Promise<any>;
create: (params?: ActionParams, options?: any) => Promise<any>;
update: (params?: ActionParams, options?: any) => Promise<any>;
destroy: (params?: ActionParams, options?: any) => Promise<any>;
[name: string]: (params?: ActionParams, options?: any) => Promise<any>;
}
// TODO 待改进,提供一个封装度更完整的 SDKrequest 可以自由替换
class ApiClient {
resource(name: string): Resource {
const proxy: any = new Proxy(
{},
{
get(target, method, receiver) {
return (params: ActionParams = {}, options: any = {}) => {
let {
associatedKey,
resourceKey,
filter,
sorter,
sort = [],
values,
...restParams
} = params;
let url = `/${name}`;
sort = sort || [];
options.params = restParams;
if (['list', 'get', 'export'].indexOf(method as string) !== -1) {
options.method = 'get';
} else {
options.method = 'post';
options.data = values;
}
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}`;
}
if (filter) {
options.params['filter'] = JSON.stringify(filter);
}
if (sorter) {
sort = [];
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;