1
0
mirror of synced 2026-04-14 21:19:18 +08:00

feat(data-source): 数据源中新增app属性,http数据源新增钩子

This commit is contained in:
roymondchen
2023-08-29 17:12:34 +08:00
parent 0865cf4952
commit c5a1c2db76
4 changed files with 29 additions and 0 deletions

View File

@@ -17,6 +17,7 @@
*/
import EventEmitter from 'events';
import type Core from '@tmagic/core';
import type { CodeBlockContent, DataSchema } from '@tmagic/schema';
import type { DataSourceOptions } from '@data-source/types';
@@ -34,12 +35,15 @@ export default class DataSource extends EventEmitter {
public data: Record<string, any> = {};
public app: Core;
private fields: DataSchema[] = [];
private methods: CodeBlockContent[] = [];
constructor(options: DataSourceOptions) {
super();
this.app = options.app;
this.id = options.schema.id;
this.setFields(options.schema.fields);
this.setMethods(options.schema.methods || []);

View File

@@ -74,12 +74,15 @@ export default class HttpDataSource extends DataSource {
public httpOptions: HttpOptions;
private fetch?: RequestFunction;
private beforeRequest: ((...args: any[]) => any)[] = [];
private afterRequest: ((...args: any[]) => any)[] = [];
constructor(options: HttpDataSourceOptions) {
const { options: httpOptions, ...dataSourceOptions } = options.schema;
super({
schema: dataSourceOptions,
app: options.app,
});
this.schema = options.schema;
@@ -90,6 +93,16 @@ export default class HttpDataSource extends DataSource {
} else if (typeof globalThis.fetch === 'function') {
this.fetch = webRequest;
}
this.getMethods().forEach((method) => {
if (typeof method.content !== 'function') return;
if (method.timing === 'beforeRequest') {
this.beforeRequest.push(method.content);
}
if (method.timing === 'afterRequest') {
this.afterRequest.push(method.content);
}
});
}
public async init() {
@@ -101,11 +114,19 @@ export default class HttpDataSource extends DataSource {
}
public async request(options: HttpOptions) {
await Promise.all(
this.beforeRequest.map((method) => method({ options, params: {}, dataSource: this, app: this.app })),
);
const res = await this.fetch?.({
...this.httpOptions,
...options,
});
await Promise.all(
this.afterRequest.map((method) => method({ res, options, params: {}, dataSource: this, app: this.app })),
);
if (this.schema.responseOptions?.dataPath) {
const data = getValueByKeyPath(this.schema.responseOptions.dataPath, res);
this.setData(data);