@nestjs/core
Version:
The core of NestJS, a TypeScript framework for Node.js backends: modules, dependency injection and the request pipeline, on Express, Fastify or node:http.
50 lines (49 loc) • 2.24 kB
JavaScript
import { STATIC_CONTEXT } from '../injector/constants.js';
import { getClassRef } from './class-ref-registry.js';
import { isFunction } from '@nestjs/common/internal';
export class ContextCreator {
createContext(instance, callback, metadataKey, contextId = STATIC_CONTEXT, inquirerId) {
const globalMetadata = this.getGlobalMetadata &&
this.getGlobalMetadata(contextId, inquirerId);
const classMetadata = this.reflectClassMetadata(instance, metadataKey);
const methodMetadata = this.reflectMethodMetadata(callback, metadataKey);
return [
...this.createConcreteContext(globalMetadata || [], contextId, inquirerId),
...this.createConcreteContext(classMetadata, contextId, inquirerId),
...this.createConcreteContext(methodMetadata, contextId, inquirerId),
];
}
reflectClassMetadata(instance, metadataKey) {
return Reflect.getMetadata(metadataKey, getClassRef(instance));
}
reflectMethodMetadata(callback, metadataKey) {
return Reflect.getMetadata(metadataKey, callback);
}
/**
* Returns the enhancer to run for one bound as a class: the instance that
* the container holds for it. The class itself is used only when that
* instance doesn't implement the method and the class has a static one of
* that name, so a static method no longer takes the place of the instance.
*/
pickEnhancer(metatype, instance, methodKey) {
if (instance && isFunction(instance[methodKey])) {
return instance;
}
if (isFunction(metatype[methodKey])) {
return metatype;
}
return instance ?? null;
}
getContextId(contextId, instanceWrapper) {
return contextId.getParent
? contextId.getParent({
token: instanceWrapper.token,
// A transient instance belongs to the consumer it was created for,
// which is not necessarily durable, so it is never shared through
// a durable sub-tree
isTreeDurable: !instanceWrapper.isTransient &&
instanceWrapper.isDependencyTreeDurable(),
})
: contextId;
}
}