1 | import { Pool } from 'pg';
|
2 | import { migrateUp, createDB, sql, readMigrationsFromDir, SchemaConstraint } from './Orm/PostgresqlDriver';
|
3 | import { sleep } from './utils';
|
4 | import { logger } from './logger';
|
5 |
|
6 | export interface DBOptions {
|
7 | config: {
|
8 | user: string | undefined;
|
9 | password: string | undefined;
|
10 | database: string | undefined;
|
11 | host?: string;
|
12 | port?: number | string | number;
|
13 | createIfNotExists?: boolean;
|
14 | };
|
15 | schema: string;
|
16 | errorEntityNotFound: unknown;
|
17 | }
|
18 |
|
19 | export async function dbInit<DBSchema extends SchemaConstraint>(projectDir: string, options: DBOptions) {
|
20 | const config = options.config;
|
21 | const pool = new Pool({
|
22 | password: config.password,
|
23 | user: config.user,
|
24 | database: config.database,
|
25 | host: config.host,
|
26 | port: typeof config.port === 'string' ? Number(config.port) : config.port,
|
27 | });
|
28 | const db = await createDB<DBSchema>(pool);
|
29 | while (true) {
|
30 | try {
|
31 | await db.query(sql`SELECT 1`);
|
32 | break;
|
33 | } catch (e) {
|
34 | logger.info('Postgres is unavailable', e);
|
35 | await sleep(1000);
|
36 | }
|
37 | }
|
38 | const migrations = await readMigrationsFromDir(projectDir + '/migrations/');
|
39 | await migrateUp(db, migrations);
|
40 | return { db, pool };
|
41 | }
|