tachybase_todo/packages/client/src/resource.ts

82 lines
1.9 KiB
TypeScript
Raw Normal View History

2021-07-23 18:08:44 +08:00
import { request } from './schemas';
2021-05-23 08:38:08 +08:00
export interface ResourceOptions {
resourceName: string;
associatedKey?: any;
associatedName?: string;
resourceKey?: any;
}
export interface GetOptions {
resourceKey?: any;
appends?: string[];
}
export interface SaveOptions {
resourceKey?: any;
}
export interface ListOptions {
}
export class Resource {
protected options: ResourceOptions;
constructor(options: string | ResourceOptions) {
if (typeof options === 'string') {
this.options = { resourceName: options }
} else {
this.options = options;
}
}
list(options: ListOptions = {}) {
const { resourceName } = this.options;
2021-07-23 18:08:44 +08:00
return request(`${resourceName}:list`);
2021-05-23 08:38:08 +08:00
}
get(options: GetOptions = {}) {
const resourceKey = options.resourceKey || this.options.resourceKey;
const { resourceName } = this.options;
if (!resourceKey) {
return Promise.resolve({ data: {} });
}
2021-07-23 18:08:44 +08:00
return request(`${resourceName}:get/${resourceKey}`);
2021-05-23 08:38:08 +08:00
}
save(values: any, options: SaveOptions = {}) {
const resourceKey = options.resourceKey || this.options.resourceKey;
const { resourceName } = this.options;
2021-07-23 18:08:44 +08:00
const url = `${resourceName}:${resourceKey ? `update/${resourceKey}` : 'create'}`;
2021-05-23 08:38:08 +08:00
return request(url, {
method: 'post',
data: values,
});
}
2021-07-23 18:08:44 +08:00
destroy(filter: any) {
const { resourceName } = this.options;
const url = `${resourceName}:destroy`;
return request(url, {
method: 'get',
params: {
filter
},
});
}
2021-05-23 08:38:08 +08:00
static make(options: string | Resource | ResourceOptions) {
if (typeof options === 'string') {
return new Resource({ resourceName: options });
}
if (options instanceof Resource) {
return options;
}
if (typeof options === 'object' && options.resourceName) {
return new Resource(options);
}
throw 'resource 参数错误';
}
}