chore: cache the database calls and return the cached one if available
Signed-off-by: blam <ben@blam.sh>
This commit is contained in:
@@ -113,7 +113,11 @@ describe('DatabaseManager', () => {
|
||||
},
|
||||
},
|
||||
};
|
||||
const manager = DatabaseManager.fromConfig(new ConfigReader(config));
|
||||
let manager: DatabaseManager;
|
||||
|
||||
beforeEach(() => {
|
||||
manager = DatabaseManager.fromConfig(new ConfigReader(config));
|
||||
});
|
||||
|
||||
it('connects to a plugin database using default config', async () => {
|
||||
const pluginId = 'pluginwithoutconfig';
|
||||
@@ -340,6 +344,15 @@ describe('DatabaseManager', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('returns the same client for the same pluginId', async () => {
|
||||
const client1 = await manager.forPlugin('plugin1').getClient();
|
||||
const client2 = await manager.forPlugin('plugin1').getClient();
|
||||
|
||||
expect(mocked(createDatabaseClient)).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(client1).toBe(client2);
|
||||
});
|
||||
|
||||
it('uses plugin connection as base if default client is different from plugin client', async () => {
|
||||
const pluginId = 'differentclient';
|
||||
await manager.forPlugin(pluginId).getClient();
|
||||
|
||||
@@ -84,6 +84,7 @@ export class DatabaseManager {
|
||||
private readonly config: Config,
|
||||
private readonly prefix: string = 'backstage_plugin_',
|
||||
private readonly options?: DatabaseManagerOptions,
|
||||
private readonly databaseCache: Map<string, Knex> = new Map(),
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -307,6 +308,9 @@ export class DatabaseManager {
|
||||
* plugin
|
||||
*/
|
||||
private async getDatabase(pluginId: string): Promise<Knex> {
|
||||
if (this.databaseCache.has(pluginId)) {
|
||||
return this.databaseCache.get(pluginId)!;
|
||||
}
|
||||
const pluginConfig = new ConfigReader(
|
||||
this.getConfigForPlugin(pluginId) as JsonObject,
|
||||
);
|
||||
@@ -344,7 +348,7 @@ export class DatabaseManager {
|
||||
|
||||
const client = createDatabaseClient(pluginConfig, databaseClientOverrides);
|
||||
this.startKeepaliveLoop(pluginId, client);
|
||||
|
||||
this.databaseCache.set(pluginId, client);
|
||||
return client;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user