-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
68 lines (60 loc) · 1.51 KB
/
Copy pathindex.ts
File metadata and controls
68 lines (60 loc) · 1.51 KB
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
import type { DatabaseConfig } from '@infrastructure/config/index.js';
import { Sequelize } from 'sequelize';
import { getLogger, getRequestLogger } from '@infrastructure/logging/index.js';
const databaseLogger = getLogger('database');
/**
* Class for creating database connection
*/
export default class SequelizeOrm {
/**
* Database configuration
*/
private config: DatabaseConfig;
/**
* Database instance
*/
private readonly conn: Sequelize;
/**
* Constructor for class
* @param databaseConfig - database config
*/
constructor(databaseConfig: DatabaseConfig) {
this.config = databaseConfig;
this.conn = new Sequelize(this.config.dsn, {
benchmark: true,
logging: (message, timing) => {
const logger = getRequestLogger('database');
logger.info(
{ durationMs: timing },
message
);
},
define: {
/**
* Use snake_case for fields in db, but camelCase in code
*/
underscored: true,
},
});
}
/**
* Test the connection by trying to authenticate
*/
public async authenticate(): Promise<void> {
/**
* Make sure that database is connected
*/
try {
await this.conn.authenticate();
databaseLogger.info(`Database connected to ${this.conn.config.host}:${this.conn.config.port}`);
} catch (error) {
databaseLogger.error(error);
}
}
/**
* Get database connection
*/
public get connection(): Sequelize {
return this.conn;
}
}