add shared database connection helpers
This commit is contained in:
@@ -35,6 +35,7 @@
|
||||
"express": "^4.17.1",
|
||||
"knex": "^0.21.1",
|
||||
"pg": "^8.3.0",
|
||||
"pg-connection-string": "^2.3.0",
|
||||
"sqlite3": "^4.2.0",
|
||||
"winston": "^3.2.1"
|
||||
},
|
||||
|
||||
@@ -23,13 +23,13 @@
|
||||
*/
|
||||
|
||||
import {
|
||||
createDatabase,
|
||||
createServiceBuilder,
|
||||
loadBackendConfig,
|
||||
getRootLogger,
|
||||
useHotMemoize,
|
||||
} from '@backstage/backend-common';
|
||||
import { ConfigReader, AppConfig } from '@backstage/config';
|
||||
import knex, { PgConnectionConfig } from 'knex';
|
||||
import healthcheck from './plugins/healthcheck';
|
||||
import auth from './plugins/auth';
|
||||
import catalog from './plugins/catalog';
|
||||
@@ -47,38 +47,10 @@ function makeCreateEnv(loadedConfigs: AppConfig[]) {
|
||||
|
||||
return (plugin: string): PluginEnvironment => {
|
||||
const logger = getRootLogger().child({ type: 'plugin', plugin });
|
||||
// Supported DBs are sqlite and postgres
|
||||
const isPg = [
|
||||
'POSTGRES_USER',
|
||||
'POSTGRES_HOST',
|
||||
'POSTGRES_PASSWORD',
|
||||
].every(key => config.getOptional(`backend.${key}`));
|
||||
|
||||
let knexConfig;
|
||||
|
||||
if (isPg) {
|
||||
knexConfig = {
|
||||
client: 'pg',
|
||||
useNullAsDefault: true,
|
||||
connection: {
|
||||
port: config.getOptionalNumber('backend.POSTGRES_PORT'),
|
||||
host: config.getString('backend.POSTGRES_HOST'),
|
||||
user: config.getString('backend.POSTGRES_USER'),
|
||||
password: config.getString('backend.POSTGRES_PASSWORD'),
|
||||
database: `backstage_plugin_${plugin}`,
|
||||
} as PgConnectionConfig,
|
||||
};
|
||||
} else {
|
||||
knexConfig = {
|
||||
client: 'sqlite3',
|
||||
connection: ':memory:',
|
||||
useNullAsDefault: true,
|
||||
};
|
||||
}
|
||||
|
||||
const database = knex(knexConfig);
|
||||
database.client.pool.on('createSuccess', (_eventId: any, resource: any) => {
|
||||
resource.run('PRAGMA foreign_keys = ON', () => {});
|
||||
const database = createDatabase(config.getConfig('backend.database'), {
|
||||
connection: {
|
||||
database: `backstage_plugin_${plugin}`,
|
||||
},
|
||||
});
|
||||
return { logger, database, config };
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user