forked from Offspend/public-hiring-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataSource.ts
63 lines (53 loc) · 1.94 KB
/
dataSource.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
import { registerAs } from "@nestjs/config";
import { config as dotenvConfig } from "dotenv";
import { join } from "path";
import { DataSource, DataSourceOptions } from "typeorm";
dotenvConfig({ path: ".env" });
const dataSourceOptions: DataSourceOptions = {
type: "postgres",
port: parseInt(
`${process.env.NODE_ENV === "test" ? process.env.DATABASE_TEST_PORT : process.env.DATABASE_PORT}`
),
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
synchronize: false,
logging: false,
entities: [join(__dirname, "../src/**/*.entity.{js,ts}")],
migrations: [join(__dirname, "../migrations", "*.*")],
migrationsTableName: "migrations",
migrationsRun: process.env.MIGRATIONS_RUN === "true",
};
export const typeorm = registerAs("typeorm", () => dataSourceOptions);
export class GreenlyDataSource {
private static dataSource: DataSource;
private static testDataSource: DataSource;
public static getInstance() {
if (process.env.NODE_ENV === "test") {
if (this.testDataSource) {
console.log(`testDataSource already set for ${process.env.NODE_ENV}`);
return this.testDataSource;
}
this.testDataSource = new DataSource(dataSourceOptions);
return this.testDataSource;
}
if (this.dataSource) {
console.log(`dataSource already set for ${process.env.NODE_ENV}`);
return this.dataSource;
}
this.dataSource = new DataSource(dataSourceOptions);
return this.dataSource;
}
public static async cleanDatabase(): Promise<void> {
try {
const entities = dataSource.entityMetadatas;
const tableNames = entities
.map((entity) => `"${entity.tableName}"`)
.join(", ");
await dataSource.query(`TRUNCATE ${tableNames} CASCADE;`);
} catch (error) {
throw new Error(`ERROR: Cleaning test database: ${error}`);
}
}
}
export const dataSource = GreenlyDataSource.getInstance();