-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathservice.ts
More file actions
42 lines (35 loc) · 1.3 KB
/
service.ts
File metadata and controls
42 lines (35 loc) · 1.3 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
import postgres from "postgres";
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import { join } from "path";
import { ConfigService } from "src/config/service";
import { LoggerService } from "src/logger/service";
import { Service } from "typedi";
@Service()
export class PostgresService {
private isReady = false;
private drizzleDB: ReturnType<typeof drizzle>;
public get db() {
if (!this.isReady) {
throw new Error("Database is not ready yet");
}
return this.drizzleDB;
}
constructor(
private readonly configService: ConfigService,
private readonly loggerService: LoggerService,
) {
this.loggerService.logger.info("Initializing Postgres database");
const { POSTGRES_URI } = this.configService.env();
const queryClient = postgres(POSTGRES_URI);
this.drizzleDB = drizzle(queryClient);
this.loggerService.logger.info("Database migration started");
}
public async migrate() {
if (this.isReady) throw new Error("Database is already ready");
this.loggerService.logger.info("Database migration started");
await migrate(this.drizzleDB, { migrationsFolder: join(__dirname, "../../db/migrations") });
this.loggerService.logger.info("Database migration complete");
this.isReady = true;
}
}