Skip to content

Commit

Permalink
feat(core): createInstance() accepts 3rd param cacheInstance (default…
Browse files Browse the repository at this point in the history
… true)
  • Loading branch information
waitingsong committed Aug 9, 2022
1 parent 94ddd69 commit 38bd79f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 6 deletions.
14 changes: 8 additions & 6 deletions packages/core/src/common/dataSourceManager.ts
Expand Up @@ -75,16 +75,18 @@ export abstract class DataSourceManager<T> {
return this.checkConnected(this.getDataSource(dataSourceName));
}

public async createInstance(config, clientName): Promise<T | void> {
public async createInstance(
config,
clientName,
cacheInstance = true
): Promise<T | void> {
// options.default will be merge in to options.clients[id]
config = extend(true, {}, this.options['default'], config);
const client = await this.createDataSource(config, clientName);
if (client) {
if (clientName) {
this.dataSource.set(clientName, client);
}
return client;
if (cacheInstance && clientName && client) {
this.dataSource.set(clientName, client);
}
return client;
}

/**
Expand Down
44 changes: 44 additions & 0 deletions packages/core/test/common/dataSourceManager.test.ts
Expand Up @@ -110,6 +110,50 @@ describe('test/common/dataSourceManager.test.ts', () => {
expect(instance.getDataSource('test')).toMatchSnapshot();
});

it('should createInstance() with cacheInstance: default true', async () => {
class EntityA {}

const instance = new CustomDataSourceFactory();
expect(instance.getName()).toEqual('test');

const name ='test'
await instance.createInstance({
host: 'localhost', //数据库地址,默认本机
port:'3306',
dialect: 'mysql',
pool: { //连接池设置
max: 5, //最大连接数
min: 0, //最小连接数
idle: 10000
},
entities: [EntityA, EntityA, '/abc']
}, name)
expect(instance.getDataSourceNames()).toEqual([name]);
expect(instance.getDataSource(name)).toMatchSnapshot();
});

it('should createInstance() with cacheInstance: false', async () => {
class EntityA {}

const instance = new CustomDataSourceFactory();
expect(instance.getName()).toEqual('test');

const name ='test'
await instance.createInstance({
host: 'localhost', //数据库地址,默认本机
port:'3306',
dialect: 'mysql',
pool: { //连接池设置
max: 5, //最大连接数
min: 0, //最小连接数
idle: 10000
},
entities: [EntityA, EntityA, '/abc']
}, name, false)
expect(instance.getDataSourceNames()).not.toEqual([name]);
expect(instance.getDataSource(name)).toBeUndefined();
});

it('should test will got error when no data source', async () => {
const instance = new CustomDataSourceFactory();
let e;
Expand Down

0 comments on commit 38bd79f

Please sign in to comment.