Skip to content

Commit

Permalink
feat(core): instantiate non-static custom classes
Browse files Browse the repository at this point in the history
Allows us to construct request-scoped custom classes by passing a `contextId` to `moduleRef.create`
  • Loading branch information
rickdgeerling committed Sep 4, 2023
1 parent 2d13d08 commit a85aa06
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
9 changes: 8 additions & 1 deletion packages/core/injector/module-ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,10 @@ export abstract class ModuleRef extends AbstractInstanceResolver {
options?: ModuleRefGetOrResolveOpts,
): Promise<TResult | Array<TResult>>;

public abstract create<T = any>(type: Type<T>): Promise<T>;
public abstract create<T = any>(
type: Type<T>,
contextId?: ContextId,
): Promise<T>;

public introspect<T = any>(
token: Type<T> | string | symbol,
Expand All @@ -151,6 +154,7 @@ export abstract class ModuleRef extends AbstractInstanceResolver {
protected async instantiateClass<T = any>(
type: Type<T>,
moduleRef: Module,
contextId?: ContextId,
): Promise<T> {
const wrapper = new InstanceWrapper({
name: type && type.name,
Expand All @@ -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);
Expand All @@ -176,6 +182,7 @@ export abstract class ModuleRef extends AbstractInstanceResolver {
moduleRef,
undefined,
callback,
contextId,
);
} catch (err) {
reject(err);
Expand Down
10 changes: 7 additions & 3 deletions packages/core/injector/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -633,11 +634,14 @@ export class Module {
);
}

public async create<T = any>(type: Type<T>): Promise<T> {
public async create<T = any>(
type: Type<T>,
contextId?: ContextId,
): Promise<T> {
if (!(type && isFunction(type) && type.prototype)) {
throw new InvalidClassException(type);
}
return this.instantiateClass<T>(type, self);
return this.instantiateClass<T>(type, self, contextId);
}
};
}
Expand Down

0 comments on commit a85aa06

Please sign in to comment.