From a85aa06070e0c7410c5350a2a5fb309dfe157bfc Mon Sep 17 00:00:00 2001 From: Rick Dutour Geerling Date: Mon, 4 Sep 2023 14:08:01 +0200 Subject: [PATCH] feat(core): instantiate non-static custom classes Allows us to construct request-scoped custom classes by passing a `contextId` to `moduleRef.create` --- packages/core/injector/module-ref.ts | 9 ++++++++- packages/core/injector/module.ts | 10 +++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/packages/core/injector/module-ref.ts b/packages/core/injector/module-ref.ts index 83aa9c891f8..2a0e4f465e8 100644 --- a/packages/core/injector/module-ref.ts +++ b/packages/core/injector/module-ref.ts @@ -128,7 +128,10 @@ export abstract class ModuleRef extends AbstractInstanceResolver { options?: ModuleRefGetOrResolveOpts, ): Promise>; - public abstract create(type: Type): Promise; + public abstract create( + type: Type, + contextId?: ContextId, + ): Promise; public introspect( token: Type | string | symbol, @@ -151,6 +154,7 @@ export abstract class ModuleRef extends AbstractInstanceResolver { protected async instantiateClass( type: Type, moduleRef: Module, + contextId?: ContextId, ): Promise { const wrapper = new InstanceWrapper({ name: type && type.name, @@ -166,6 +170,8 @@ export abstract class ModuleRef extends AbstractInstanceResolver { const properties = await this.injector.resolveProperties( wrapper, moduleRef, + undefined, + contextId, ); const instance = new type(...instances); this.injector.applyProperties(instance, properties); @@ -176,6 +182,7 @@ export abstract class ModuleRef extends AbstractInstanceResolver { moduleRef, undefined, callback, + contextId, ); } catch (err) { reject(err); diff --git a/packages/core/injector/module.ts b/packages/core/injector/module.ts index 6d0d51e8911..222569470df 100644 --- a/packages/core/injector/module.ts +++ b/packages/core/injector/module.ts @@ -37,8 +37,9 @@ import { isDurable } from '../helpers/is-durable'; import { UuidFactory } from '../inspector/uuid-factory'; import { CONTROLLER_ID_KEY } from './constants'; import { NestContainer } from './container'; -import { InstanceWrapper } from './instance-wrapper'; +import { ContextId, InstanceWrapper } from './instance-wrapper'; import { ModuleRef, ModuleRefGetOrResolveOpts } from './module-ref'; +import { Injector } from './injector'; export class Module { private readonly _id: string; @@ -633,11 +634,14 @@ export class Module { ); } - public async create(type: Type): Promise { + public async create( + type: Type, + contextId?: ContextId, + ): Promise { if (!(type && isFunction(type) && type.prototype)) { throw new InvalidClassException(type); } - return this.instantiateClass(type, self); + return this.instantiateClass(type, self, contextId); } }; }