-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.ts
42 lines (34 loc) · 939 Bytes
/
db.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
import { Pool } from "pg";
import { cache } from "./cache";
let database: Pool;
const connectDb = async () => {
try {
database = new Pool({
user: process.env.PGUSER,
host: process.env.PGHOST,
database: process.env.PGDATABASE,
password: process.env.PGPASSWORD,
port: Number.parseInt(process.env.PGPORT as string) ?? 5432,
keepAlive: true,
});
database.on("error", (err: any) =>
console.log("### NODE-PG ERROR ###\n", err)
);
} catch (error) {
console.log(error);
}
};
const closeConnection = async (_: any) => {
//Needs _ argument, otherwise it would be called after server start for some reason...
if (database) {
await database.end();
}
if (cache) {
cache.close();
}
process.exit(); // Exit with default success-code '0'.
};
connectDb();
process.once("SIGTERM", closeConnection);
process.once("SIGINT", closeConnection);
export { database };