@@ -3,20 +3,49 @@ import { AbstractStartedContainer, ExecResult, GenericContainer, StartedTestCont
33const MONGODB_PORT = 27017 ;
44
55export class MongoDBContainer extends GenericContainer {
6+ private username = "" ;
7+ private password = "" ;
8+ private initRs = true ;
9+
610 constructor ( image : string ) {
711 super ( image ) ;
812 this . withExposedPorts ( MONGODB_PORT )
9- . withCommand ( [ "--replSet" , "rs0" ] )
1013 . withWaitStrategy ( Wait . forLogMessage ( / .* w a i t i n g f o r c o n n e c t i o n s .* / i) )
1114 . withStartupTimeout ( 120_000 ) ;
1215 }
1316
17+ public withReplicaSetEnabled ( enabled : boolean ) : this {
18+ this . initRs = enabled ;
19+ return this ;
20+ }
21+
22+ public withUsername ( username : string ) : this {
23+ this . username = username ;
24+ return this ;
25+ }
26+
27+ public withPassword ( password : string ) : this {
28+ this . password = password ;
29+ return this ;
30+ }
31+
1432 public override async start ( ) : Promise < StartedMongoDBContainer > {
15- return new StartedMongoDBContainer ( await super . start ( ) ) ;
33+ if ( this . username && this . password ) {
34+ this . withEnvironment ( {
35+ MONGO_INITDB_ROOT_USERNAME : this . username ,
36+ MONGO_INITDB_ROOT_PASSWORD : this . password ,
37+ } ) ;
38+ }
39+ if ( this . initRs ) {
40+ this . withCommand ( [ "--replSet" , "rs0" ] ) ;
41+ }
42+ return new StartedMongoDBContainer ( await super . start ( ) , this . username , this . password ) ;
1643 }
1744
1845 protected override async containerStarted ( startedTestContainer : StartedTestContainer ) : Promise < void > {
19- await this . initReplicaSet ( startedTestContainer ) ;
46+ if ( this . initRs ) {
47+ await this . initReplicaSet ( startedTestContainer ) ;
48+ }
2049 }
2150
2251 private async initReplicaSet ( startedTestContainer : StartedTestContainer ) {
@@ -58,11 +87,18 @@ export class MongoDBContainer extends GenericContainer {
5887}
5988
6089export class StartedMongoDBContainer extends AbstractStartedContainer {
61- constructor ( startedTestContainer : StartedTestContainer ) {
90+ private readonly username : string = "" ;
91+ private readonly password : string = "" ;
92+
93+ constructor ( startedTestContainer : StartedTestContainer , username : string , password : string ) {
6294 super ( startedTestContainer ) ;
95+ this . username = username ;
96+ this . password = password ;
6397 }
6498
6599 public getConnectionString ( ) : string {
100+ if ( this . username && this . password )
101+ return `mongodb://${ this . username } :${ this . password } @${ this . getHost ( ) } :${ this . getMappedPort ( MONGODB_PORT ) } ` ;
66102 return `mongodb://${ this . getHost ( ) } :${ this . getMappedPort ( MONGODB_PORT ) } ` ;
67103 }
68104}
0 commit comments