-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
create-db-connection.ts
79 lines (66 loc) · 1.72 KB
/
create-db-connection.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
76
77
78
79
import { knex, Knex } from 'knex';
import path from 'path';
import { promisify } from 'util';
export type Credentials = {
filename?: string;
host?: string;
port?: number;
database?: string;
user?: string;
password?: string;
ssl?: boolean;
options__encrypt?: boolean;
};
export default function createDBConnection(
client: 'sqlite3' | 'mysql' | 'pg' | 'oracledb' | 'mssql' | 'cockroachdb',
credentials: Credentials
): Knex<any, unknown[]> {
let connection: Knex.Config['connection'] = {};
if (client === 'sqlite3') {
const { filename } = credentials;
connection = {
filename: filename as string,
};
} else {
const { host, port, database, user, password } = credentials as Credentials;
connection = {
host: host,
port: Number(port),
database: database,
user: user,
password: password,
};
if (client === 'pg' || client === 'cockroachdb') {
const { ssl } = credentials as Credentials;
connection['ssl'] = ssl;
}
if (client === 'mssql') {
const { options__encrypt } = credentials as Credentials;
(connection as Knex.MsSqlConnectionConfig)['options'] = {
encrypt: options__encrypt,
};
}
}
const knexConfig: Knex.Config = {
client: client,
connection: connection,
seeds: {
extension: 'js',
directory: path.resolve(__dirname, '../../database/seeds/'),
},
pool: {},
};
if (client === 'sqlite3') {
knexConfig.useNullAsDefault = true;
}
if (client === 'cockroachdb') {
knexConfig.pool!.afterCreate = async (conn: any, callback: any) => {
const run = promisify(conn.query.bind(conn));
await run('SET serial_normalization = "sql_sequence"');
await run('SET default_int_size = 4');
callback(null, conn);
};
}
const db = knex(knexConfig);
return db;
}