Upgrade to mikro-orm v5
After migrating to mikro-orm v5 (from ^4.5.9), my integration tests are suddenly failing with the following error:
ValidationError: You cannot call em.flush() from inside lifecycle hook handlers
at Function.cannotCommit (/path/to/my/project/node_modules/pg-mem/node_modules/@mikro-orm/core/errors.js:77:16)
at UnitOfWork.commit (/path/to/my/project/node_modules/pg-mem/node_modules/@mikro-orm/core/unit-of-work/UnitOfWork.js:168:44)
at SqlEntityManager.flush (/path/to/my/project/node_modules/pg-mem/node_modules/@mikro-orm/core/EntityManager.js:497:36)
at SqlEntityManager.persistAndFlush (/path/to/my/project/node_modules/pg-mem/node_modules/@mikro-orm/core/EntityManager.js:449:36)
The FAQ page states that this can happen when the request context is not set up properly. In my case, it is already set up:
app.use((req, res, next) => RequestContext.create(orm.em, next));
I refer to the Entity Manager like this: orm.em. This appears to be safe based on its description: The global EntityManager instance. If you are using RequestContext helper, it will automatically pick the request specific context under the hood. In other words, it doesn't seem necessary to call RequestContext.getEntityManager() manually - in fact, if I do, it has no effect on the error.
I also use ava which runs tests concurrently, each in its own sandbox. My test files start with a before-all hook which calls a setup function. This function creates an instance of Express that is then shared and invoked by every test case using supertest.
If my test file only contains a single test, it passes. However, as soon as I add a second test I get the above error. This is key - I can see that orm.em.persistAndFlush is indeed called twice - but it's called twice in separate concurrent requests, meaning RequestContext.create also gets invoked twice.
I noticed pg-mem is currently on ^4.5.3 of mikro. I also looked at the current adapter, but nothing stands out. As an experiment, if I manually replace pg-mem/node_modules/@mikro-orm with the v5 of node_modules/@mikro-orm, I get
TypeError {
message: 'builder.generateDdlCommands is not a function',
}
› SchemaGenerator.dump (/path/to/my/project/node_modules/pg-mem/node_modules/@mikro-orm/knex/schema/SchemaGenerator.js:447:35)
› SchemaGenerator.getCreateSchemaSQL (/path/to/my/project/node_modules/pg-mem/node_modules/@mikro-orm/knex/schema/SchemaGenerator.js:61:31)
› SchemaGenerator.createSchema (/path/to/my/project/node_modules/pg-mem/node_modules/@mikro-orm/knex/schema/SchemaGenerator.js:26:32)
Could this by any chance be related to version mismatch? Thanks
package.json:
"@mikro-orm/core": "^5.1.2",
"@mikro-orm/postgresql": "^5.1.2",
"pg-mem": "^2.3.5",