This repository has been archived by the owner on Jul 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreproduction-alt.ts
73 lines (62 loc) · 2.56 KB
/
reproduction-alt.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
import "reflect-metadata";
import { BaseEntity, Entity, PrimaryKey, SerializedPrimaryKey } from "@mikro-orm/core";
import { EntityRepository, ObjectId } from "@mikro-orm/mongodb";
import { InjectRepository, MikroOrmModule } from "@mikro-orm/nestjs";
import { INestApplicationContext, Injectable, Module, Scope } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { LoggerModule, PinoLogger } from "nestjs-pino";
@Entity({ collection: "entities" })
export class MongoEntity extends BaseEntity<MongoEntity, "id"> {
@PrimaryKey()
public _id!: ObjectId;
@SerializedPrimaryKey()
public id!: string;
}
@Injectable()
export class MongoService {
constructor(@InjectRepository(MongoEntity) public readonly repository: EntityRepository<MongoEntity>) {}
}
@Module({ imports: [MikroOrmModule.forFeature([MongoEntity])], providers: [MongoService] })
export class MongoModule {}
@Module({
imports: [
LoggerModule.forRoot(),
MikroOrmModule.forRootAsync({
inject: [PinoLogger],
useFactory: (logger: PinoLogger) => {
logger.setContext("MikroOrm");
return {
type: "mongo",
clientUrl: "mongodb://127.0.0.1:27017/dbName", // local dockerized MongoDB v3 instance
dbName: "dbName",
entities: [MongoEntity],
debug: ["query"], // Log all queries
logger: message => logger.info(message),
};
},
// If scope is not passed, using repository throws ValidationError
scope: Scope.REQUEST,
}),
MongoModule,
],
})
class AppModule {}
let applicationContext: INestApplicationContext;
if (require.main === module) {
(async () => {
applicationContext = await NestFactory.createApplicationContext(AppModule);
applicationContext = await applicationContext.init();
// If scope is passed to MikroOrmModule.forRootAsync, applicationContext.get works but repository is undefined
// .resolve must be used instead
const mongoService = await applicationContext.resolve(MongoService);
await mongoService.repository.findAll(); // With scope it works
// With scope each resolved new MongoService instance gets EntityManager with _id incremented by 1
console.info("EntityManager _id is %d", (await applicationContext.resolve(MongoService)).repository.getEntityManager()._id)
console.info("EntityManager _id is %d", (await applicationContext.resolve(MongoService)).repository.getEntityManager()._id)
await applicationContext.close();
process.exit(0)
})().catch(async error => {
await applicationContext?.close();
throw error;
});
}