feat: beforeAddDataSource hook (#4810)

This commit is contained in:
ChengLei Shao 2024-07-05 08:46:35 +08:00 committed by GitHub
parent 5dc626d2d6
commit a1b2c25a94
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 30 additions and 0 deletions

View File

@ -165,6 +165,24 @@ describe('example', () => {
await app.destroy(); await app.destroy();
}); });
it('should call beforeAddDataSource hook', async () => {
const hook = vi.fn();
const app = await createMockServer({
acl: false,
resourcer: {
prefix: '/api/',
},
name: 'update-filter',
});
app.dataSourceManager.beforeAddDataSource(hook);
// it should be called on main datasource
expect(hook).toBeCalledTimes(1);
await app.destroy();
});
it('should register every datasource instance', async () => { it('should register every datasource instance', async () => {
const hook = vi.fn(); const hook = vi.fn();

View File

@ -21,6 +21,7 @@ export class DataSourceManager {
factory: DataSourceFactory = new DataSourceFactory(); factory: DataSourceFactory = new DataSourceFactory();
protected middlewares = []; protected middlewares = [];
private onceHooks: Array<DataSourceHook> = []; private onceHooks: Array<DataSourceHook> = [];
private beforeAddHooks: Array<DataSourceHook> = [];
constructor(public options = {}) { constructor(public options = {}) {
this.dataSources = new Map(); this.dataSources = new Map();
@ -32,6 +33,10 @@ export class DataSourceManager {
} }
async add(dataSource: DataSource, options: any = {}) { async add(dataSource: DataSource, options: any = {}) {
for (const hook of this.beforeAddHooks) {
hook(dataSource);
}
await dataSource.load(options); await dataSource.load(options);
this.dataSources.set(dataSource.name, dataSource); this.dataSources.set(dataSource.name, dataSource);
@ -71,6 +76,13 @@ export class DataSourceManager {
return this.factory.create(type, options); return this.factory.create(type, options);
} }
beforeAddDataSource(hook: DataSourceHook) {
this.beforeAddHooks.push(hook);
for (const dataSource of this.dataSources.values()) {
hook(dataSource);
}
}
afterAddDataSource(hook: DataSourceHook) { afterAddDataSource(hook: DataSourceHook) {
this.addHookAndRun(hook); this.addHookAndRun(hook);
} }