-
Notifications
You must be signed in to change notification settings - Fork 368
/
database.ts
75 lines (62 loc) · 2.56 KB
/
database.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import knex from 'knex';
import type { Knex } from 'knex';
import { retry } from '../utils/retry.js';
export function getDbConfig({ timeoutMs }: { timeoutMs: number }): Knex.Config<any> {
return {
client: process.env['NANGO_DB_CLIENT'] || 'pg',
connection: process.env['NANGO_DATABASE_URL'] || {
host: process.env['NANGO_DB_HOST'] || (process.env['SERVER_RUN_MODE'] === 'DOCKERIZED' ? 'nango-db' : 'localhost'),
port: +(process.env['NANGO_DB_PORT'] || 5432),
user: process.env['NANGO_DB_USER'] || 'nango',
database: process.env['NANGO_DB_NAME'] || 'nango',
password: process.env['NANGO_DB_PASSWORD'] || 'nango',
ssl: process.env['NANGO_DB_SSL'] != null && process.env['NANGO_DB_SSL'].toLowerCase() === 'true' ? { rejectUnauthorized: false } : undefined,
statement_timeout: timeoutMs
},
pool: {
min: parseInt(process.env['NANGO_DB_POOL_MIN'] || '2'),
max: parseInt(process.env['NANGO_DB_POOL_MAX'] || '20')
},
searchPath: 'nango'
};
}
export class KnexDatabase {
knex: Knex;
constructor({ timeoutMs } = { timeoutMs: 60000 }) {
const dbConfig = getDbConfig({ timeoutMs });
this.knex = knex(dbConfig);
}
async migrate(directory: string): Promise<any> {
return retry(async () => await this.knex.migrate.latest({ directory: directory, tableName: '_nango_auth_migrations', schemaName: this.schema() }), {
maxAttempts: 4,
delayMs: (attempt) => 500 * attempt
});
}
schema() {
return 'nango';
}
}
const db = new KnexDatabase();
export default db;
export { db as database };
export const schema = (): Knex.QueryBuilder => db.knex.queryBuilder();
export const dbNamespace = '_nango_';
export const multipleMigrations = async (): Promise<void> => {
try {
await db.knex.raw(`CREATE SCHEMA IF NOT EXISTS ${db.schema()}`);
const [_, pendingMigrations] = await db.knex.migrate.list({
directory: String(process.env['NANGO_DB_MIGRATION_FOLDER'])
});
if (pendingMigrations.length === 0) {
console.log('No pending migrations, skipping migration step.');
} else {
console.log('Migrations pending, running migrations.');
await db.knex.migrate.latest({
directory: String(process.env['NANGO_DB_MIGRATION_FOLDER'])
});
console.log('Migrations completed.');
}
} catch (error: any) {
console.error(error.message || error);
}
};