chore: datasource manager api (#4124)

* chore: datasource manager api

* chore: interface

* chore: api

* chore: datasource api
This commit is contained in:
ChengLei Shao 2024-04-22 22:23:41 +08:00 committed by GitHub
parent 3413c6c6d4
commit 320d4fef07
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 40 additions and 3 deletions

View File

@ -3,6 +3,30 @@ import { DataSource } from '../data-source';
import { ICollectionManager } from '../types';
describe('data source factory', () => {
it('should register data source type from dataSourceManager', async () => {
class MockDataSource extends DataSource {
createCollectionManager(options?: any): ICollectionManager {
return undefined;
}
}
const app = await createMockServer({
acl: false,
resourcer: {
prefix: '/api/',
},
name: 'test-app-0',
});
app.dataSourceManager.registerDataSourceType('mock', MockDataSource);
expect(app.dataSourceManager.getDataSourceType('mock')).toBe(MockDataSource);
const ds = app.dataSourceManager.buildDataSourceByType('mock');
expect(ds).toBeInstanceOf(MockDataSource);
});
it('should register data source type', async () => {
class MockDataSource extends DataSource {
createCollectionManager(options?: any): ICollectionManager {

View File

@ -6,11 +6,12 @@ type DataSourceHook = (dataSource: DataSource) => void;
export class DataSourceManager {
dataSources: Map<string, DataSource>;
/**
* @internal
*/
factory: DataSourceFactory = new DataSourceFactory();
onceHooks: Array<DataSourceHook> = [];
protected middlewares = [];
private onceHooks: Array<DataSourceHook> = [];
constructor(public options = {}) {
this.dataSources = new Map();
@ -49,6 +50,18 @@ export class DataSourceManager {
};
}
registerDataSourceType(type: string, DataSourceClass: typeof DataSource) {
this.factory.register(type, DataSourceClass);
}
getDataSourceType(type: string): typeof DataSource | undefined {
return this.factory.getClass(type);
}
buildDataSourceByType(type: string, options: any = {}): DataSource {
return this.factory.create(type, options);
}
afterAddDataSource(hook: DataSourceHook) {
this.addHookAndRun(hook);
}