-
-
Notifications
You must be signed in to change notification settings - Fork 206
/
Copy pathpostgresql-container.ts
executable file
·88 lines (75 loc) · 2.32 KB
/
postgresql-container.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
80
81
82
83
84
85
86
87
88
import { AbstractStartedContainer, GenericContainer, StartedTestContainer, Wait } from "testcontainers";
const POSTGRES_PORT = 5432;
export class PostgreSqlContainer extends GenericContainer {
private database = "test";
private username = "test";
private password = "test";
constructor(image = "postgres:13.3-alpine") {
super(image);
this.withExposedPorts(POSTGRES_PORT);
this.withWaitStrategy(Wait.forHealthCheck());
this.withStartupTimeout(120_000);
}
public withDatabase(database: string): this {
this.database = database;
return this;
}
public withUsername(username: string): this {
this.username = username;
return this;
}
public withPassword(password: string): this {
this.password = password;
return this;
}
public override async start(): Promise<StartedPostgreSqlContainer> {
this.withEnvironment({
POSTGRES_DB: this.database,
POSTGRES_USER: this.username,
POSTGRES_PASSWORD: this.password,
});
if (!this.healthCheck) {
this.withHealthCheck({
test: ["CMD-SHELL", `PGPASSWORD=${this.password} psql -U ${this.username} -d ${this.database} -c 'SELECT 1;'`],
interval: 250,
timeout: 1000,
retries: 1000,
});
}
return new StartedPostgreSqlContainer(await super.start(), this.database, this.username, this.password);
}
}
export class StartedPostgreSqlContainer extends AbstractStartedContainer {
constructor(
startedTestContainer: StartedTestContainer,
private readonly database: string,
private readonly username: string,
private readonly password: string
) {
super(startedTestContainer);
}
public getPort(): number {
return super.getMappedPort(POSTGRES_PORT);
}
public getDatabase(): string {
return this.database;
}
public getUsername(): string {
return this.username;
}
public getPassword(): string {
return this.password;
}
/**
* @returns A connection URI in the form of `postgres[ql]://[username[:password]@][host[:port],]/database`
*/
public getConnectionUri(): string {
const url = new URL("", "postgres://");
url.hostname = this.getHost();
url.port = this.getPort().toString();
url.pathname = this.getDatabase();
url.username = this.getUsername();
url.password = this.getPassword();
return url.toString();
}
}