Skip to content

Commit

Permalink
feat(core): add disableContextResolution option to em.fork()
Browse files Browse the repository at this point in the history
Use this flag to ignore current async context - this is required if we want
to call `em.fork()` inside the `getContext` handler.

Closes #3338
  • Loading branch information
B4nan committed Jul 29, 2022
1 parent e56a259 commit 94442f9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
4 changes: 3 additions & 1 deletion packages/core/src/EntityManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -881,7 +881,7 @@ export class EntityManager<D extends IDatabaseDriver = IDatabaseDriver> {
* Returns new EntityManager instance with its own identity map
*/
fork(options: ForkOptions = {}): D[typeof EntityManagerType] {
const em = this.getContext(false);
const em = options.disableContextResolution ? this : this.getContext(false);
options.clear ??= true;
options.useContext ??= false;
options.freshEventManager ??= false;
Expand Down Expand Up @@ -1197,5 +1197,7 @@ export interface ForkOptions {
useContext?: boolean;
/** do we want to use fresh EventManager instance? defaults to false (global instance) */
freshEventManager?: boolean;
/** use this flag to ignore current async context - this is required if we want to call `em.fork()` inside the `getContext` handler */
disableContextResolution?: boolean;
flushMode?: FlushMode;
}
9 changes: 8 additions & 1 deletion tests/EntityManager.mongo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -438,9 +438,16 @@ describe('EntityManagerMongo', () => {
expect(fork.getMetadata()).toBe(orm.em.getMetadata());
expect(fork.getUnitOfWork().getIdentityMap()).toEqual(new IdentityMap());

// request context is not started so we can use UoW and EF getters
// request context is not started, so we can use UoW and EF getters
expect(fork.getUnitOfWork().getIdentityMap()).not.toBe(orm.em.getUnitOfWork().getIdentityMap());
expect(fork.getEntityFactory()).not.toBe(orm.em.getEntityFactory());

const spy = jest.spyOn(EntityManager.prototype, 'getContext');
const fork2 = orm.em.fork({ disableContextResolution: true });
expect(spy).toBeCalledTimes(2);

const fork3 = orm.em.fork({ disableContextResolution: false });
expect(spy).toBeCalledTimes(5);
});

test('findOne with empty where will throw', async () => {
Expand Down

0 comments on commit 94442f9

Please sign in to comment.