@nestjs/core
- Version 12.1.3
- Published
- 696 kB
- 5 dependencies
- MIT license
Install
npm i @nestjs/coreyarn add @nestjs/corepnpm add @nestjs/coreOverview
Nest - modern, fast, powerful node.js web framework (@core)
Index
Variables
Functions
Classes
AbstractHttpAdapter
- all()
- appendHeader()
- applyVersionFilter()
- beforeClose()
- clearCookie()
- close()
- cookieSigner
- copy()
- createMiddlewareFactory()
- delete()
- enableCors()
- end()
- get()
- getHeader()
- getHttpServer()
- getInstance()
- getOnRouteTriggered()
- getRequestHostname()
- getRequestMethod()
- getRequestUrl()
- getType()
- head()
- httpServer
- init()
- initHttpServer()
- instance
- isHeadersSent()
- listen()
- lock()
- mapException()
- mkcol()
- move()
- normalizePath()
- onRouteTriggered
- options()
- patch()
- post()
- propfind()
- proppatch()
- put()
- query()
- redirect()
- registerParserMiddleware()
- registerSecurityHook()
- render()
- reply()
- search()
- setCookie()
- setErrorHandler()
- setHeader()
- setHttpServer()
- setInstance()
- setNotFoundHandler()
- setOnRequestHook()
- setOnResponseHook()
- setOnRouteTriggered()
- setViewEngine()
- status()
- unlock()
- use()
- useStaticAssets()
ApplicationConfig
- addGlobalFilter()
- addGlobalGuard()
- addGlobalInterceptor()
- addGlobalPipe()
- addGlobalRequestFilter()
- addGlobalRequestGuard()
- addGlobalRequestInterceptor()
- addGlobalRequestPipe()
- enableVersioning()
- getCookieSigner()
- getGlobalFilters()
- getGlobalGuards()
- getGlobalInterceptors()
- getGlobalPipes()
- getGlobalPrefix()
- getGlobalPrefixOptions()
- getGlobalPreRequestHooks()
- getGlobalRequestFilters()
- getGlobalRequestGuards()
- getGlobalRequestInterceptors()
- getGlobalRequestPipes()
- getIoAdapter()
- getRouteConflictPolicy()
- getRouteResolutionStrategy()
- getVersioning()
- registerPreRequestHook()
- setCookieSigner()
- setGlobalPrefix()
- setGlobalPrefixOptions()
- setIoAdapter()
- setRouteConflictPolicy()
- setRouteResolutionStrategy()
- useGlobalFilters()
- useGlobalGuards()
- useGlobalInterceptors()
- useGlobalPipes()
NestApplication
- applyOptions()
- connectMicroservice()
- createServer()
- dispose()
- enableCors()
- enableCsrfProtection()
- enableVersioning()
- getHttpAdapter()
- getHttpServer()
- getMicroservices()
- getUnderlyingHttpServer()
- getUrl()
- init()
- listen()
- logger
- preloadLazyPackages()
- prepareClose()
- registerHttpServer()
- registerModules()
- registerParserMiddleware()
- registerRouter()
- registerRouterHooks()
- registerWsModule()
- setBaseViewsDir()
- setGlobalPrefix()
- setViewEngine()
- startAllMicroservices()
- use()
- useBodyParser()
- useGlobalFilters()
- useGlobalGuards()
- useGlobalInterceptors()
- useGlobalPipes()
- useSecurityHeaders()
- useStaticAssets()
- useWebSocketAdapter()
NestApplicationContext
- appOptions
- assertNotInPreviewMode()
- callBeforeShutdownHook()
- callBootstrapHook()
- callDestroyHook()
- callInitHook()
- callShutdownHook()
- close()
- container
- dispose()
- enableShutdownHooks()
- flushLogs()
- flushLogsIfAutoFlushEnabled()
- flushLogsOnOverride()
- get()
- init()
- injector
- instanceLinksHost
- isInitialized
- listenToShutdownSignals()
- logger
- prepareClose()
- registerRequestByContextId()
- resolve()
- select()
- selectContextModule()
- shutdown()
- unsubscribeFromProcessSignals()
- useLogger()
NestContainer
- addController()
- addDynamicMetadata()
- addDynamicModules()
- addExportedProviderOrModule()
- addGlobalModule()
- addImport()
- addInjectable()
- addModule()
- addProvider()
- applicationConfig
- bindGlobalModuleToModule()
- bindGlobalScope()
- bindGlobalsToImports()
- clear()
- contextOptions
- getDynamicMetadataByToken()
- getHttpAdapterHostRef()
- getHttpAdapterRef()
- getInternalCoreModuleRef()
- getModuleByKey()
- getModuleCompiler()
- getModules()
- getModuleTokenFactory()
- isGlobalModule()
- registerCoreModuleRef()
- registerRequestProvider()
- replace()
- replaceModule()
- serializedGraph
- setHttpAdapter()
Interfaces
Type Aliases
Variables
variable APP_FILTER
const APP_FILTER: string;variable APP_GUARD
const APP_GUARD: string;variable APP_INTERCEPTOR
const APP_INTERCEPTOR: string;variable APP_PIPE
const APP_PIPE: string;variable INQUIRER
const INQUIRER: string;variable NestFactory
const NestFactory: NestFactoryStatic;Use NestFactory to create an application instance.
### Specifying an entry module
Pass the required *root module* for the application via the module parameter. By convention, it is usually called
ApplicationModule. Starting with this module, Nest assembles the dependency graph and begins the process of Dependency Injection and instantiates the classes needed to launch your application.
variable REQUEST
const REQUEST: string;Functions
function createContextId
createContextId: () => ContextId;function repl
repl: ( module: Type | DynamicModule, replOptions?: ReplOptions) => Promise<import('node:repl').REPLServer>;Classes
class AbstractHttpAdapter
abstract class AbstractHttpAdapter<TServer = any, TRequest = any, TResponse = any> implements HttpServer<TRequest, TResponse> {}Base class for HTTP platform adapters (see
ExpressAdapterandFastifyAdapterfor reference implementations).It implements the HttpServer contract that the Nest core relies on, and that interface is where each method's calling conventions are documented: when the core invokes it, with which arguments, and what it expects back. This class only adds:
- default implementations that delegate to the wrapped framework
instance(use(), the HTTP-verb methods,listen()) or are inert (init(),normalizePath(),mapException(),beforeClose(), thesetOn*Hook()setters), plus an Express-style,use()-basedregisterSecurityHook(); - storage for the native server (httpServer) and the framework instance (instance), with their accessors; -setCookie()andclearCookie(), implemented once on top ofappendHeader(), so they behave the same on every platform; - the introspection hooks used by instrumentation tooling.Every remaining HttpServer member is declared abstract here, even the ones the interface marks optional, so subclasses cannot forget them.
setBaseViewsDir(),useBodyParser()andisRouteOrderSensitive()are not declared on this class; implement them when the platform supports them (see HttpServer for what the core does when they are absent).Keep in mind that the core also reads and writes properties of the request object (
body,params,query,headers, ...), that Server-Sent Events write directly to the Node.js response, and thatapp.listen()and the WebSocket adapters use the value returned by AbstractHttpAdapter.getHttpServer as a Node.jsnet.Server; see the HttpServer documentation for details.See Also
[HTTP adapter](https://docs.nestjs.com/faq/http-adapter)
constructor
constructor(instance?: any);Parameter instance
The framework application instance to delegate to (e.g. an Express
Application). Subclasses typically create a default one when none is given.
property cookieSigner
protected cookieSigner: CookieSigner;Signer built from the
cookies.secretapplication option, used by AbstractHttpAdapter.setCookie forsignedcookies.
property httpServer
protected httpServer: {};Native HTTP server created by AbstractHttpAdapter.initHttpServer and returned by AbstractHttpAdapter.getHttpServer.
property instance
protected instance?: any;property onRouteTriggered
protected onRouteTriggered: (requestMethod: RequestMethod, path: string) => void;Callback registered through AbstractHttpAdapter.setOnRouteTriggered, if any.
method all
all: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a route for every HTTP method by delegating to
instance.all(...args).See Also
method appendHeader
abstract appendHeader: (response: any, name: string, value: string) => any;Appends a value to a response header, turning it into a multi-value header (e.g. several
Set-Cookieentries) instead of replacing it. Not used by the core router; part of the base class so ecosystem packages can append headers through the adapter regardless of the platform.
method applyVersionFilter
abstract applyVersionFilter: ( handler: Function, version: VersionValue, versioningOptions: VersioningOptions) => (req: TRequest, res: TResponse, next: () => void) => Function;Guards a route handler by request version for header, media-type and custom versioning.
See Also
method beforeClose
beforeClose: () => void;Called by
app.close()before the shutdown hooks run. No-op by default; override to enter a "shutting down" state.See Also
method clearCookie
clearCookie: ( response: TResponse, name: string, options?: CookieSerializeOptions) => any;Appends a
Set-Cookieheader that expires the cookie immediately.pathanddomainmust match the ones the cookie was set with;maxAge,expiresandsignedare ignored.See Also
method close
abstract close: () => any;Stops the server; called by
app.close(). May return a promise.See Also
method copy
copy: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a WebDAV
COPYroute by delegating toinstance.copy(...args). Override when the framework exposes the verb under a different API.See Also
method createMiddlewareFactory
abstract createMiddlewareFactory: ( requestMethod: RequestMethod) => | ((path: string, callback: Function) => any) | Promise<(path: string, callback: Function) => any>;Returns the function used to mount Nest middleware for one HTTP method. May be asynchronous.
See Also
method delete
delete: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a
DELETEroute by delegating toinstance.delete(...args).See Also
method enableCors
abstract enableCors: (options?: any, prefix?: string) => any;Enables CORS. The core currently calls this with
optionsonly; theprefixparameter is reserved.See Also
method end
abstract end: (response: any, message?: string) => any;Terminates the response, optionally writing
messagefirst.See Also
method get
get: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a
GETroute by delegating toinstance.get(...args).See Also
method getHeader
abstract getHeader: (response: any, name: string) => any;Reads a response header that was set earlier. Not used by the core router; part of the base class so ecosystem packages can read headers through the adapter regardless of the platform.
method getHttpServer
getHttpServer: () => TServer;Returns the native HTTP server stored by AbstractHttpAdapter.initHttpServer (or AbstractHttpAdapter.setHttpServer).
See Also
method getInstance
getInstance: <T = any>() => T;Returns the framework application instance passed to the constructor (or set through AbstractHttpAdapter.setInstance).
See Also
method getOnRouteTriggered
getOnRouteTriggered: () => (requestMethod: RequestMethod, path: string) => void;Returns the callback registered through AbstractHttpAdapter.setOnRouteTriggered, if any. Read by the router when registering routes.
method getRequestHostname
abstract getRequestHostname: (request: any) => any;Returns the request host name, used for
@Controller({ host }).See Also
method getRequestMethod
abstract getRequestMethod: (request: any) => any;Returns the upper-case request method (
'GET','POST', ...).See Also
method getRequestUrl
abstract getRequestUrl: (request: any) => any;Returns the original request URL, including the query string.
See Also
method getType
abstract getType: () => string;Returns the platform identifier (
'express','fastify') that ecosystem packages branch on.See Also
method head
head: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a
HEADroute by delegating toinstance.head(...args).See Also
method init
init: () => Promise<void>;Asynchronous setup hook, awaited by
NestFactory.create()and again byapp.init(), so overrides must be idempotent. No-op by default.See Also
method initHttpServer
abstract initHttpServer: (options: NestApplicationOptions) => any;Creates the native server and stores it in
httpServer, honoring thehttpsOptions,forceCloseConnectionsandreturn503OnClosingapplication options. Called once when the application is constructed.See Also
method isHeadersSent
abstract isHeadersSent: (response: any) => any;Reports whether response headers have already been flushed. Must return synchronously.
See Also
method listen
listen: { (port: string | number, callback?: () => void): any; (port: string | number, hostname: string, callback?: () => void): any;};Starts listening by delegating to
instance.listen(port, hostname, callback). The core always passes its own callback as the last argument and expects it to be invoked once the server is bound, or with anErroron failure. Override when the framework instance does not expose a Node-stylelisten(), e.g. to callhttpServer.listen()instead.See Also
method lock
lock: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a WebDAV
LOCKroute by delegating toinstance.lock(...args). Override when the framework exposes the verb under a different API.See Also
method mapException
mapException: (error: unknown) => unknown;Translates a framework-native error into something the exception filters understand. Invoked by the global exception layer with every error it receives, before it reaches the filters; the returned value is what the filters see. Returns the error unchanged by default. The built-in adapters map, for instance, body-parser
SyntaxErrors toBadRequestException.
method mkcol
mkcol: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a WebDAV
MKCOLroute by delegating toinstance.mkcol(...args). Override when the framework exposes the verb under a different API.See Also
method move
move: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a WebDAV
MOVEroute by delegating toinstance.move(...args). Override when the framework exposes the verb under a different API.See Also
method normalizePath
normalizePath: (path: string) => string;Converts and validates a route path before registration. Returns the path unchanged by default; override to translate Nest's path syntax to the router's and to throw on invalid paths.
See Also
method options
options: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers an
OPTIONSroute by delegating toinstance.options(...args).See Also
method patch
patch: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a
PATCHroute by delegating toinstance.patch(...args).See Also
method post
post: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a
POSTroute by delegating toinstance.post(...args).See Also
method propfind
propfind: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a WebDAV
PROPFINDroute by delegating toinstance.propfind(...args). Override when the framework exposes the verb under a different API.See Also
method proppatch
proppatch: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a WebDAV
PROPPATCHroute by delegating toinstance.proppatch(...args). Override when the framework exposes the verb under a different API.See Also
method put
put: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a
PUTroute by delegating toinstance.put(...args).See Also
method query
query: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a
QUERYroute by delegating toinstance.query(...args). Override when the framework exposes the verb under a different API.See Also
method redirect
abstract redirect: (response: any, statusCode: number, url: string) => any;Issues a redirect (
@Redirect()).See Also
method registerParserMiddleware
abstract registerParserMiddleware: (prefix?: string, rawBody?: boolean) => any;Registers the default JSON and URL-encoded body parsers, exposing
req.rawBodywhenrawBodyistrue.See Also
method registerSecurityHook
registerSecurityHook: (hook: SecurityRequestHook<TRequest>) => any;Installs the request hook of the built-in HTTP security features as a global middleware (
use()), which fits Express-like frameworks: the hook gets the request and the response, and a rejection is handed tonext(error), i.e. to the exception layer. Override when the framework offers an earlier request hook (the Fastify adapter usesonRequest).See Also
method render
abstract render: (response: any, view: string, options: any) => any;Renders a view template (
@Render()).See Also
method reply
abstract reply: (response: any, body: any, statusCode?: number) => any;Sends the response body, handling empty bodies,
StreamableFile, objects (as JSON) and primitives.See Also
method search
search: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a
SEARCHroute by delegating toinstance.search(...args). Override when the framework exposes the verb under a different API.See Also
method setCookie
setCookie: ( response: TResponse, name: string, value: string, options?: CookieSerializeOptions) => any;Appends a
Set-Cookieheader through AbstractHttpAdapter.appendHeader, so every cookie set during a request is sent, on every platform. The value is percent-encoded,pathdefaults to/andmaxAgeis in seconds (not milliseconds, unlike Express'res.cookie()); withsigned: true, the value is signed with the firstcookies.secret.Throws a
TypeErrorwhen the name, the value or an attribute is not valid per RFC 6265 (which rules out header injection through;, CR or LF) or whensameSite: 'none'orpartitionedis set withoutsecure, and anErrorwhensignedis set but no secret is configured.See Also
method setErrorHandler
abstract setErrorHandler: (handler: Function, prefix?: string) => any;Installs the global exception layer.
See Also
method setHeader
abstract setHeader: (response: any, name: string, value: string) => any;Sets (replaces) a response header (
@Header()).See Also
method setHttpServer
setHttpServer: (httpServer: TServer) => void;Replaces the native HTTP server returned by AbstractHttpAdapter.getHttpServer. Mostly useful for tests and for adapters that obtain the server from elsewhere.
method setInstance
setInstance: <T = any>(instance: T) => void;Replaces the framework application instance that the default method implementations delegate to.
method setNotFoundHandler
abstract setNotFoundHandler: ( handler: Function, prefix?: string, excludedRoutes?: RouteInfo[]) => any;Installs the catch-all handler for unmatched requests.
See Also
method setOnRequestHook
setOnRequestHook: (onRequestHook: Function) => void;Registers a hook to run at the start of every request. No-op by default; the built-in adapters accept a
(req, res, done) => void | Promise<void>function and calldone()to continue processing. Intended for instrumentation and devtools.
method setOnResponseHook
setOnResponseHook: (onResponseHook: Function) => void;Registers a hook to run once a response has been sent. No-op by default; the built-in adapters accept a
(req, res) => void | Promise<void>function. Intended for instrumentation and devtools.
method setOnRouteTriggered
setOnRouteTriggered: ( onRouteTriggered: (requestMethod: RequestMethod, path: string) => void) => void;Registers a callback that the router invokes right before each route handler runs, with the resolved
RequestMethodand the route path as declared (before AbstractHttpAdapter.normalizePath). The router wraps every handler at registration time, so the callback must be set beforeapp.init()to take effect. Intended for instrumentation and devtools; there is no need to override it.
method setViewEngine
abstract setViewEngine: (engine: string) => any;Configures the template engine used by AbstractHttpAdapter.render; pass-through for
app.setViewEngine().See Also
method status
abstract status: (response: any, statusCode: number) => any;Sets the status code without sending the response.
See Also
method unlock
unlock: { (handler: RequestHandler): any; (path: any, handler: RequestHandler): any;};Registers a WebDAV
UNLOCKroute by delegating toinstance.unlock(...args). Override when the framework exposes the verb under a different API.See Also
method use
use: (...args: any[]) => any;Registers a global middleware by delegating to
instance.use(...args).See Also
method useStaticAssets
abstract useStaticAssets: (...args: any[]) => any;Serves static files; pass-through for
app.useStaticAssets().See Also
class ApplicationConfig
class ApplicationConfig {}constructor
constructor(ioAdapter?: any);method addGlobalFilter
addGlobalFilter: (filter: ExceptionFilter) => void;method addGlobalGuard
addGlobalGuard: (guard: CanActivate) => void;method addGlobalInterceptor
addGlobalInterceptor: (interceptor: NestInterceptor) => void;method addGlobalPipe
addGlobalPipe: (pipe: PipeTransform<any>) => void;method addGlobalRequestFilter
addGlobalRequestFilter: (wrapper: InstanceWrapper<ExceptionFilter>) => void;method addGlobalRequestGuard
addGlobalRequestGuard: (wrapper: InstanceWrapper<CanActivate>) => void;method addGlobalRequestInterceptor
addGlobalRequestInterceptor: (wrapper: InstanceWrapper<NestInterceptor>) => void;method addGlobalRequestPipe
addGlobalRequestPipe: (wrapper: InstanceWrapper<PipeTransform>) => void;method enableVersioning
enableVersioning: (options: VersioningOptions) => void;method getCookieSigner
getCookieSigner: () => CookieSigner | undefined;method getGlobalFilters
getGlobalFilters: () => ExceptionFilter[];method getGlobalGuards
getGlobalGuards: () => CanActivate[];method getGlobalInterceptors
getGlobalInterceptors: () => NestInterceptor[];method getGlobalPipes
getGlobalPipes: () => PipeTransform<any>[];method getGlobalPrefix
getGlobalPrefix: () => string;method getGlobalPrefixOptions
getGlobalPrefixOptions: () => GlobalPrefixOptions<ExcludeRouteMetadata>;method getGlobalPreRequestHooks
getGlobalPreRequestHooks: () => PreRequestHook[];method getGlobalRequestFilters
getGlobalRequestFilters: () => InstanceWrapper<ExceptionFilter>[];method getGlobalRequestGuards
getGlobalRequestGuards: () => InstanceWrapper<CanActivate>[];method getGlobalRequestInterceptors
getGlobalRequestInterceptors: () => InstanceWrapper<NestInterceptor>[];method getGlobalRequestPipes
getGlobalRequestPipes: () => InstanceWrapper<PipeTransform>[];method getIoAdapter
getIoAdapter: () => WebSocketAdapter;method getRouteConflictPolicy
getRouteConflictPolicy: () => RouteConflictPolicy | undefined;method getRouteResolutionStrategy
getRouteResolutionStrategy: () => RouteResolutionStrategy | undefined;method getVersioning
getVersioning: () => VersioningOptions | undefined;method registerPreRequestHook
registerPreRequestHook: (...hooks: PreRequestHook[]) => void;method setCookieSigner
setCookieSigner: (signer: CookieSigner | undefined) => void;method setGlobalPrefix
setGlobalPrefix: (prefix: string) => void;method setGlobalPrefixOptions
setGlobalPrefixOptions: ( options: GlobalPrefixOptions<ExcludeRouteMetadata>) => void;method setIoAdapter
setIoAdapter: (ioAdapter: WebSocketAdapter) => void;method setRouteConflictPolicy
setRouteConflictPolicy: (policy: RouteConflictPolicy | undefined) => void;method setRouteResolutionStrategy
setRouteResolutionStrategy: ( strategy: RouteResolutionStrategy | undefined) => void;method useGlobalFilters
useGlobalFilters: (...filters: ExceptionFilter[]) => void;method useGlobalGuards
useGlobalGuards: (...guards: CanActivate[]) => void;method useGlobalInterceptors
useGlobalInterceptors: (...interceptors: NestInterceptor[]) => void;method useGlobalPipes
useGlobalPipes: (...pipes: PipeTransform<any>[]) => void;class BaseExceptionFilter
class BaseExceptionFilter<T = any> implements ExceptionFilter<T> {}constructor
constructor(applicationRef?: any);property applicationRef
protected readonly applicationRef?: any;property httpAdapterHost
protected readonly httpAdapterHost?: HttpAdapterHost< AbstractHttpAdapter<any, any, any>>;method catch
catch: (exception: T, host: ArgumentsHost) => void;method handleUnknownError
handleUnknownError: ( exception: T, host: ArgumentsHost, applicationRef: AbstractHttpAdapter | HttpServer) => void;method isExceptionObject
isExceptionObject: (err: any) => err is Error;method isHttpError
isHttpError: (err: any) => err is { statusCode: number; message: string };Checks if the thrown error is a FastifyError or comes from the "http-errors" library.
Parameter err
error object
class ContextIdFactory
class ContextIdFactory {}method apply
static apply: (strategy: ContextIdStrategy) => void;Registers a custom context id strategy that lets you attach a parent context id to the existing context id object.
Parameter strategy
strategy instance
method create
static create: () => ContextId;Generates a context identifier based on the request object.
method getByRequest
static getByRequest: <T extends Record<any, any> = any>( request: T, propsToInspect?: string[]) => ContextId;Generates a random identifier to track asynchronous execution context.
Parameter request
request object
class DiscoveryModule
class DiscoveryModule {}class DiscoveryService
class DiscoveryService {}constructor
constructor(modulesContainer: ModulesContainer);method createDecorator
static createDecorator: <T>() => DiscoverableDecorator<T>;Creates a decorator that can be used to decorate classes and methods with metadata. The decorator will also add the class to the collection of discoverable classes (by metadata key). Decorated classes can be discovered using the
getProvidersandgetControllersmethods.Returns
A decorator function.
method getControllers
getControllers: ( options?: DiscoveryOptions, modules?: Module[]) => InstanceWrapper[];Returns an array of instance wrappers (controllers). Depending on the options, the array will contain either all controllers or only controllers with the specified metadata key.
Parameter options
Discovery options.
Parameter modules
A list of modules to filter by.
Returns
An array of instance wrappers (controllers).
method getMetadataByDecorator
getMetadataByDecorator: <T extends DiscoverableDecorator<any>>( decorator: T, instanceWrapper: InstanceWrapper, methodKey?: string) => T extends DiscoverableDecorator<infer R> ? R : T;Retrieves metadata from the specified instance wrapper.
Parameter decorator
The decorator to retrieve metadata of.
Parameter instanceWrapper
Reference to the instance wrapper.
Parameter methodKey
An optional method key to retrieve metadata from.
Returns
Discovered metadata.
method getModules
protected getModules: (options?: DiscoveryOptions) => Module[];Returns a list of modules to be used for discovery.
method getProviders
getProviders: ( options?: DiscoveryOptions, modules?: Module[]) => InstanceWrapper[];Returns an array of instance wrappers (providers). Depending on the options, the array will contain either all providers or only providers with the specified metadata key.
Parameter options
Discovery options.
Parameter modules
A list of modules to filter by.
Returns
An array of instance wrappers (providers).
class ExternalContextCreator
class ExternalContextCreator {}constructor
constructor( guardsContextCreator: GuardsContextCreator, guardsConsumer: GuardsConsumer, interceptorsContextCreator: InterceptorsContextCreator, interceptorsConsumer: InterceptorsConsumer, modulesContainer: ModulesContainer, pipesContextCreator: PipesContextCreator, pipesConsumer: PipesConsumer, filtersContextCreator: ExternalExceptionFilterContext);method create
create: < TParamsMetadata extends ParamsMetadata = ParamsMetadata, TContext extends string = ContextType>( instance: Controller, callback: (...args: unknown[]) => unknown, methodName: string, metadataKey?: string, paramsFactory?: ParamsFactory, contextId?: ContextId, inquirerId?: string, options?: ExternalContextOptions, contextType?: TContext) => (...args: any[]) => Promise<any>;method createGuardsFn
createGuardsFn: <TContext extends string = ContextType>( guards: any[], instance: Controller, callback: (...args: any[]) => any, contextType?: TContext) => Function | null;method createPipesFn
createPipesFn: ( pipes: PipeTransform[], paramsOptions: (ParamProperties & { metatype?: unknown })[]) => (args: unknown[], ...params: unknown[]) => Promise<void>;method exchangeKeysForValues
exchangeKeysForValues: <TMetadata = any>( keys: string[], metadata: TMetadata, moduleContext: string, paramsFactory: ParamsFactory, contextId?: ContextId, inquirerId?: string, contextFactory?: ( args: unknown[] ) => import('./execution-context-host.js').ExecutionContextHost) => ParamProperties[];method fromContainer
static fromContainer: (container: NestContainer) => ExternalContextCreator;method getContextModuleKey
getContextModuleKey: (moduleCtor: Function | undefined) => string;method getMetadata
getMetadata: <TMetadata, TContext extends string = ContextType>( instance: Controller, methodName: string, metadataKey?: string, paramsFactory?: ParamsFactory, contextType?: TContext) => ExternalHandlerMetadata;method getParamValue
getParamValue: <T>( value: T, metadata: ArgumentMetadata, pipes: PipeTransform[]) => Promise<any>;method registerRequestProvider
registerRequestProvider: <T = any>(request: T, contextId: ContextId) => void;method transformToResult
transformToResult: (resultOrDeferred: any) => Promise<any>;class GraphInspector
class GraphInspector {}constructor
constructor(container: NestContainer);method insertAttachedEnhancer
insertAttachedEnhancer: (wrapper: InstanceWrapper) => void;method insertClassNode
insertClassNode: ( moduleRef: Module, wrapper: InstanceWrapper, type: Exclude<Node['metadata']['type'], 'module'>) => void;method insertEnhancerMetadataCache
insertEnhancerMetadataCache: (entry: EnhancerMetadataCacheEntry) => void;method insertEntrypointDefinition
insertEntrypointDefinition: <T>( definition: Entrypoint<T>, parentId: string) => void;method insertOrphanedEnhancer
insertOrphanedEnhancer: (entry: OrphanedEnhancerDefinition) => void;method inspectInstanceWrapper
inspectInstanceWrapper: <T = any>( source: InstanceWrapper<T>, moduleRef: Module) => void;method inspectModules
inspectModules: (modules?: Map<string, Module>) => void;method registerPartial
registerPartial: (error: unknown) => void;class HttpAdapterHost
class HttpAdapterHost<T extends AbstractHttpAdapter = AbstractHttpAdapter> {}Defines the
HttpAdapterHostobject.HttpAdapterHostwraps the underlying platform-specificHttpAdapter. TheHttpAdapteris a wrapper around the underlying native HTTP server library (e.g., Express). TheHttpAdapterHostobject provides methods togetandsetthe underlying HttpAdapter.See Also
[Http adapter](https://docs.nestjs.com/faq/http-adapter)
property httpAdapter
httpAdapter: AbstractHttpAdapter<any, any, any>;Accessor for the underlying
HttpAdapterExample 1
const httpAdapter = adapterHost.httpAdapter;
property init$
readonly init$: Observable<void>;Observable that allows to subscribe to the
initevent. This event is emitted when the HTTP application is initialized.
property listen$
readonly listen$: Observable<void>;Observable that allows to subscribe to the
listenevent. This event is emitted when the HTTP application is listening for incoming requests.
property listening
listening: boolean;Returns a boolean indicating whether the application is listening for incoming requests.
class InitializeOnPreviewAllowlist
class InitializeOnPreviewAllowlist {}class LazyModuleLoader
class LazyModuleLoader {}constructor
constructor( dependenciesScanner: DependenciesScanner, instanceLoader: InstanceLoader<Injector>, moduleCompiler: ModuleCompiler, modulesContainer: ModulesContainer, moduleOverrides?: ModuleOverride[]);method load
load: ( loaderFn: () => | Promise<Type<unknown> | DynamicModule> | Type<unknown> | DynamicModule, loadOpts?: LazyModuleLoaderLoadOptions) => Promise<ModuleRef>;class MetadataScanner
class MetadataScanner {}method getAllFilteredMethodNames
getAllFilteredMethodNames: (prototype: object) => IterableIterator<string>;See Also
getAllMethodNames
Deprecated
method getAllMethodNames
getAllMethodNames: (prototype: object | null) => string[];method scanFromPrototype
scanFromPrototype: <T extends Injectable, R = any>( instance: T, prototype: object | null, callback: (name: string) => R) => R[];See Also
getAllMethodNames
Deprecated
class MiddlewareBuilder
class MiddlewareBuilder implements MiddlewareConsumer {}constructor
constructor( routesMapper: RoutesMapper, httpAdapter: HttpServer, routeInfoPathExtractor: RouteInfoPathExtractor);method apply
apply: ( ...middleware: Array<Type<any> | Function | Array<Type<any> | Function>>) => MiddlewareConfigProxy;method build
build: () => MiddlewareConfiguration[];method getHttpAdapter
getHttpAdapter: () => HttpServer;class ModuleRef
abstract class ModuleRef extends AbstractInstanceResolver {}constructor
constructor(container: NestContainer);property container
protected readonly container: NestContainer;property injector
protected readonly injector: Injector;property instanceLinksHost
readonly instanceLinksHost: InstanceLinksHost;method create
abstract create: <T = any>(type: Type<T>, contextId?: ContextId) => Promise<T>;method get
abstract get: { <TInput = any, TResult = TInput>( typeOrToken: Type<TInput> | Function | string | symbol ): TResult; <TInput = any, TResult = TInput>( typeOrToken: any, options: { strict?: boolean; each?: false } ): TResult; <TInput = any, TResult = TInput>( typeOrToken: any, options: { strict?: boolean; each: true } ): TResult[]; <TInput = any, TResult = TInput>( typeOrToken: any, options?: ModuleRefGetOrResolveOpts ): TResult | TResult[];};Retrieves an instance of either injectable or controller, otherwise, throws exception.
Returns
{TResult}
Retrieves a list of instances of either injectables or controllers, otherwise, throws exception.
Returns
{Array}
Retrieves an instance (or a list of instances) of either injectable or controller, otherwise, throws exception.
Returns
{TResult | Array}
method instantiateClass
protected instantiateClass: <T = any>( type: Type<T>, moduleRef: Module, contextId?: ContextId) => Promise<T>;method introspect
introspect: <T = any>(token: Type<T> | string | symbol) => IntrospectionResult;method registerRequestByContextId
registerRequestByContextId: <T = any>(request: T, contextId: ContextId) => void;method resolve
abstract resolve: { <TInput = any, TResult = TInput>( typeOrToken: Type<TInput> | Function | string | symbol ): Promise<TResult>; <TInput = any, TResult = TInput>( typeOrToken: any, contextId?: { id: number } ): Promise<TResult>; <TInput = any, TResult = TInput>( typeOrToken: any, contextId?: { id: number }, options?: { strict?: boolean; each?: false } ): Promise<TResult>; <TInput = any, TResult = TInput>( typeOrToken: any, contextId?: { id: number }, options?: { strict?: boolean; each: true } ): Promise<TResult[]>; <TInput = any, TResult = TInput>( typeOrToken: any, contextId?: { id: number }, options?: ModuleRefGetOrResolveOpts ): Promise<TResult | TResult[]>;};Resolves transient or request-scoped instance of either injectable or controller, otherwise, throws exception.
Returns
{Promise}
Resolves transient or request-scoped instances of either injectables or controllers, otherwise, throws exception.
Returns
{Promise<Array>}
Resolves transient or request-scoped instance (or a list of instances) of either injectable or controller, otherwise, throws exception.
Returns
{Promise<TResult | Array>}
class ModulesContainer
class ModulesContainer extends Map<string, Module> {}property applicationId
readonly applicationId: string;Unique identifier of the application instance.
method addRpcTarget
addRpcTarget: <T>(target: T) => void;Adds an RPC target to the registry.
Parameter target
The RPC target to add.
method getById
getById: (id: string) => Module | undefined;Retrieves a module by its identifier.
Parameter id
The identifier of the module to retrieve.
Returns
The module instance if found, otherwise undefined.
method getRpcTargetRegistry
getRpcTargetRegistry: <T>() => Observable<T>;Returns the RPC target registry as an observable. This registry contains all RPC targets registered in the application.
Returns
An observable that emits the RPC target registry.
class NestApplication
class NestApplication extends NestApplicationContext<NestApplicationOptions> implements INestApplication {}constructor
constructor( container: NestContainer, httpAdapter: HttpServer, config: ApplicationConfig, graphInspector: GraphInspector, appOptions?: NestApplicationOptions);property logger
protected readonly logger: Logger;method applyOptions
applyOptions: () => void;method connectMicroservice
connectMicroservice: <T extends object>( microserviceOptions: T, hybridAppOptions?: NestHybridApplicationOptions) => INestMicroservice;method createServer
createServer: <T = any>() => T;method dispose
protected dispose: () => Promise<void>;method enableCors
enableCors: (options?: any) => void;method enableCsrfProtection
enableCsrfProtection: (options?: CsrfProtectionOptions) => this;method enableVersioning
enableVersioning: (options?: VersioningOptions) => this;method getHttpAdapter
getHttpAdapter: () => AbstractHttpAdapter;method getHttpServer
getHttpServer: () => any;method getMicroservices
getMicroservices: () => INestMicroservice[];method getUnderlyingHttpServer
getUnderlyingHttpServer: <T>() => T;method getUrl
getUrl: () => Promise<string>;method init
init: () => Promise<this>;method listen
listen: { (port: number | string): Promise<any>; (port: string | number, hostname: string): Promise<any>;};method preloadLazyPackages
preloadLazyPackages: () => Promise<void>;Pre-load optional packages so that createNestApplication, createNestMicroservice and createHttpAdapter can stay synchronous.
method prepareClose
protected prepareClose: () => Promise<void>;method registerHttpServer
registerHttpServer: () => void;method registerModules
registerModules: () => Promise<void>;method registerParserMiddleware
registerParserMiddleware: () => void;method registerRouter
registerRouter: () => Promise<void>;method registerRouterHooks
registerRouterHooks: () => Promise<void>;method registerWsModule
registerWsModule: () => Promise<void>;method setBaseViewsDir
setBaseViewsDir: (path: string | string[]) => this;method setGlobalPrefix
setGlobalPrefix: (prefix: string, options?: GlobalPrefixOptions) => this;method setViewEngine
setViewEngine: (engineOrOptions: any) => this;method startAllMicroservices
startAllMicroservices: () => Promise<this>;method use
use: (args_0: any, args_1?: any) => this;method useBodyParser
useBodyParser: (args_0: any, args_1?: any) => this;method useGlobalFilters
useGlobalFilters: (...filters: ExceptionFilter[]) => this;method useGlobalGuards
useGlobalGuards: (...guards: CanActivate[]) => this;method useGlobalInterceptors
useGlobalInterceptors: (...interceptors: NestInterceptor[]) => this;method useGlobalPipes
useGlobalPipes: (...pipes: PipeTransform<any>[]) => this;method useSecurityHeaders
useSecurityHeaders: (options?: SecurityHeadersOptions) => this;method useStaticAssets
useStaticAssets: { (options: any): this; (path: string, options?: any): this };method useWebSocketAdapter
useWebSocketAdapter: (adapter: WebSocketAdapter) => this;class NestApplicationContext
class NestApplicationContext< TOptions extends NestApplicationContextOptions = NestApplicationContextOptions > extends AbstractInstanceResolver implements INestApplicationContext {}constructor
constructor( container: NestContainer, appOptions?: NestApplicationContextOptions, contextModule?: Module, scope?: Type<any>[]);property appOptions
protected readonly appOptions: NestApplicationContextOptions;property container
protected readonly container: NestContainer;property injector
protected injector: Injector;property instanceLinksHost
readonly instanceLinksHost: InstanceLinksHost;property isInitialized
protected isInitialized: boolean;property logger
protected readonly logger: Logger;method assertNotInPreviewMode
protected assertNotInPreviewMode: (methodName: string) => void;method callBeforeShutdownHook
protected callBeforeShutdownHook: (signal?: string) => Promise<void>;Calls the
beforeApplicationShutdownfunction on the registered modules and children.
method callBootstrapHook
protected callBootstrapHook: () => Promise<void>;Calls the
onApplicationBootstrapfunction on the registered modules and its children.
method callDestroyHook
protected callDestroyHook: () => Promise<void>;Calls the
onModuleDestroyfunction on the registered modules and its children.
method callInitHook
protected callInitHook: () => Promise<void>;Calls the
onModuleInitfunction on the registered modules and its children.
method callShutdownHook
protected callShutdownHook: (signal?: string) => Promise<void>;Calls the
onApplicationShutdownfunction on the registered modules and children.
method close
close: (signal?: string) => Promise<void>;Terminates the application
Returns
{Promise}
method dispose
protected dispose: () => Promise<void>;method enableShutdownHooks
enableShutdownHooks: ( signals?: (ShutdownSignal | string)[], options?: ShutdownHooksOptions) => this;Enables the usage of shutdown hooks. Will call the
onApplicationShutdownfunction of a provider if the process receives a shutdown signal.Repeated calls are idempotent per signal. Shutdown hooks can be re-enabled after the application context has been closed.
Parameter signals
The system signals it should listen to
Parameter options
Options for configuring shutdown hooks behavior
Returns
{this} The Nest application context instance
method flushLogs
flushLogs: () => void;Prints buffered logs and detaches buffer.
Returns
{void}
method flushLogsIfAutoFlushEnabled
protected flushLogsIfAutoFlushEnabled: () => void;method flushLogsOnOverride
flushLogsOnOverride: () => void;Define that it must flush logs right after defining a custom logger.
method get
get: { <TInput = any, TResult = TInput>( typeOrToken: Type<TInput> | Function | string | symbol ): TResult; <TInput = any, TResult = TInput>( typeOrToken: any, options: { strict?: boolean; each?: false } ): TResult; <TInput = any, TResult = TInput>( typeOrToken: any, options: { strict?: boolean; each: true } ): TResult[];};Retrieves an instance of either injectable or controller, otherwise, throws exception.
Returns
{TResult}
Retrieves a list of instances of either injectables or controllers, otherwise, throws exception.
Returns
{Array}
method init
init: () => Promise<this>;Initializes the Nest application. Calls the Nest lifecycle events.
Returns
{Promise} The NestApplicationContext instance as Promise
method listenToShutdownSignals
protected listenToShutdownSignals: ( signals: string[], options?: ShutdownHooksOptions) => void;Listens to shutdown signals by listening to process events
Parameter signals
The system signals it should listen to
Parameter options
Options for configuring shutdown hooks behavior
method prepareClose
protected prepareClose: () => Promise<void>;method registerRequestByContextId
registerRequestByContextId: <T = any>(request: T, contextId: ContextId) => void;Registers the request/context object for a given context ID (DI container sub-tree).
Returns
{void}
method resolve
resolve: { <TInput = any, TResult = TInput>( typeOrToken: Type<TInput> | Function | string | symbol ): Promise<TResult>; <TInput = any, TResult = TInput>( typeOrToken: any, contextId?: { id: number } ): Promise<TResult>; <TInput = any, TResult = TInput>( typeOrToken: any, contextId?: { id: number }, options?: { strict?: boolean; each?: false } ): Promise<TResult>; <TInput = any, TResult = TInput>( typeOrToken: any, contextId?: { id: number }, options?: { strict?: boolean; each: true } ): Promise<TResult[]>;};Resolves transient or request-scoped instance of either injectable or controller, otherwise, throws exception.
Returns
{Promise}
Resolves transient or request-scoped instances of either injectables or controllers, otherwise, throws exception.
Returns
{Promise<Array>}
method select
select: <T>( moduleType: Type<T> | DynamicModule, selectOptions?: SelectOptions) => INestApplicationContext;Allows navigating through the modules tree, for example, to pull out a specific instance from the selected module.
Returns
{INestApplicationContext}
method selectContextModule
selectContextModule: () => void;method shutdown
protected shutdown: (signal?: string) => Promise<void>;Runs the shutdown sequence, at most once per cycle. Callers that arrive while a shutdown is already in flight - a process signal delivered during an explicit
close(), or the other way round - await the very same promise instead of starting a second, concurrent teardown.Parameter signal
The system signal that triggered the shutdown
Returns
{Promise}
method unsubscribeFromProcessSignals
protected unsubscribeFromProcessSignals: () => void;Unsubscribes from shutdown signals (process events)
method useLogger
useLogger: (logger: LoggerService | LogLevel[] | false) => void;Sets custom logger service. Flushes buffered logs if auto flush is on.
Returns
{void}
class NestContainer
class NestContainer {}constructor
constructor(_applicationConfig?: ApplicationConfig, _contextOptions?: any);property applicationConfig
readonly applicationConfig: ApplicationConfig;property contextOptions
readonly contextOptions: any;property serializedGraph
readonly serializedGraph: SerializedGraph;method addController
addController: (controller: Type<any>, token: string) => void;method addDynamicMetadata
addDynamicMetadata: ( token: string, dynamicModuleMetadata: DynamicModule, scope: Type<any>[]) => Promise<void>;method addDynamicModules
addDynamicModules: (modules: any[], scope: Type<any>[]) => Promise<void>;method addExportedProviderOrModule
addExportedProviderOrModule: ( toExport: Type<any> | DynamicModule, token: string) => void;method addGlobalModule
addGlobalModule: (module: Module) => void;method addImport
addImport: ( relatedModule: Type<any> | DynamicModule, token: string) => Promise<void>;method addInjectable
addInjectable: ( injectable: Provider, token: string, enhancerSubtype: EnhancerSubtype, host?: Type<Injectable>) => | string | symbol | Function | import('./instance-wrapper.js').InstanceWrapper<unknown>;method addModule
addModule: ( metatype: ModuleMetatype, scope: ModuleScope) => Promise<{ moduleRef: Module; inserted: boolean } | undefined>;method addProvider
addProvider: ( provider: Provider, token: string, enhancerSubtype?: EnhancerSubtype) => string | symbol | Function;method bindGlobalModuleToModule
bindGlobalModuleToModule: (target: Module, globalModule: Module) => void;method bindGlobalScope
bindGlobalScope: () => void;method bindGlobalsToImports
bindGlobalsToImports: (moduleRef: Module) => void;method clear
clear: () => void;method getDynamicMetadataByToken
getDynamicMetadataByToken: { (token: string): DynamicModule; <K extends string | number | symbol>( token: string, metadataKey: K ): DynamicModule;};method getHttpAdapterHostRef
getHttpAdapterHostRef: () => import('../index.js').HttpAdapterHost< import('../index.js').AbstractHttpAdapter<any, any, any>>;method getHttpAdapterRef
getHttpAdapterRef: () => import('../index.js').AbstractHttpAdapter< any, any, any>;method getInternalCoreModuleRef
getInternalCoreModuleRef: () => Module | undefined;method getModuleByKey
getModuleByKey: (moduleKey: string) => Module | undefined;method getModuleCompiler
getModuleCompiler: () => ModuleCompiler;method getModules
getModules: () => ModulesContainer;method getModuleTokenFactory
getModuleTokenFactory: () => ModuleOpaqueKeyFactory;method isGlobalModule
isGlobalModule: ( metatype: Type<any>, dynamicMetadata?: DynamicModule) => boolean;method registerCoreModuleRef
registerCoreModuleRef: (moduleRef: Module) => void;method registerRequestProvider
registerRequestProvider: <T = any>(request: T, contextId: ContextId) => void;method replace
replace: (toReplace: any, options: { scope: any[] | null }) => void;method replaceModule
replaceModule: ( metatypeToReplace: ModuleMetatype, newMetatype: ModuleMetatype, scope: ModuleScope) => Promise<{ moduleRef: Module; inserted: boolean } | undefined>;method setHttpAdapter
setHttpAdapter: (httpAdapter: any) => void;class PartialGraphHost
class PartialGraphHost {}class Reflector
class Reflector {}Helper class providing Nest reflection capabilities.
See Also
[Reflection](https://docs.nestjs.com/guards#putting-it-all-together)
method createDecorator
static createDecorator: { <TParam>( options?: CreateDecoratorOptions<TParam> ): ReflectableDecorator<TParam>; <TParam, TTransformed>( options: CreateDecoratorWithTransformOptions<TParam, TTransformed> ): ReflectableDecorator<TParam, TTransformed>;};Creates a decorator that can be used to decorate classes and methods with metadata. Can be used as a strongly-typed alternative to
@SetMetadata.Parameter options
Decorator options.
Returns
A decorator function.
method get
get: { <T extends ReflectableDecorator<any, any>>( decorator: T, target: Type<any> | Function ): T extends ReflectableDecorator<any, infer R> ? R : unknown; <TResult = any, TKey = any>(metadataKey: TKey, target: any): TResult;};Retrieve metadata for a reflectable decorator for a specified target.
Parameter decorator
reflectable decorator created through
Reflector.createDecoratorParameter target
context (decorated object) to retrieve metadata from
Example 1
const roles = this.reflector.get(Roles, context.getHandler());Retrieve metadata for a specified key for a specified target.
Parameter metadataKey
lookup key for metadata to retrieve
Parameter target
context (decorated object) to retrieve metadata from
Example 1
const roles = this.reflector.get<string[]>('roles', context.getHandler());
method getAll
getAll: { <TParam = any, TTransformed = TParam>( decorator: ReflectableDecorator<TParam, TTransformed>, targets: (Type<any> | Function)[] ): TTransformed extends Array<any> ? TTransformed : TTransformed[]; <TResult extends any[] = any[], TKey = any>( metadataKey: TKey, targets: any[] ): TResult;};Retrieve metadata for a specified decorator for a specified set of targets.
Parameter decorator
lookup decorator for metadata to retrieve
Parameter targets
context (decorated objects) to retrieve metadata from
Retrieve metadata for a specified key for a specified set of targets.
Parameter metadataKey
lookup key for metadata to retrieve
Parameter targets
context (decorated objects) to retrieve metadata from
method getAllAndMerge
getAllAndMerge: { <TParam = any, TTransformed = TParam>( decorator: ReflectableDecorator<TParam, TTransformed>, targets: (Type<any> | Function)[] ): TTransformed extends Array<any> ? TTransformed : TTransformed extends object ? TTransformed : TTransformed[]; <TResult extends object | any[] = any[], TKey = any>( metadataKey: TKey, targets: any[] ): TResult;};Retrieve metadata for a specified decorator for a specified set of targets and merge results.
Parameter decorator
lookup decorator for metadata to retrieve
Parameter targets
context (decorated objects) to retrieve metadata from
Retrieve metadata for a specified key for a specified set of targets and merge results.
Parameter metadataKey
lookup key for metadata to retrieve
Parameter targets
context (decorated objects) to retrieve metadata from
method getAllAndOverride
getAllAndOverride: { <TParam = any, TTransformed = TParam>( decorator: ReflectableDecorator<TParam, TTransformed>, targets: (Type<any> | Function)[] ): TTransformed; <TResult = any, TKey = any>(metadataKey: TKey, targets: any[]): TResult;};Retrieve metadata for a specified decorator for a specified set of targets and return a first not undefined value.
Parameter decorator
lookup decorator for metadata to retrieve
Parameter targets
context (decorated objects) to retrieve metadata from
Retrieve metadata for a specified key for a specified set of targets and return a first not undefined value.
Parameter metadataKey
lookup key for metadata to retrieve
Parameter targets
context (decorated objects) to retrieve metadata from
class RouterModule
class RouterModule {}constructor
constructor(modulesContainer: ModulesContainer, routes: Routes);method register
static register: (routes: Routes) => DynamicModule;class SerializedGraph
class SerializedGraph {}method getNodeById
getNodeById: (id: string) => Node | undefined;method insertAttachedEnhancer
insertAttachedEnhancer: (nodeId: string) => void;method insertEdge
insertEdge: (edgeDefinition: WithOptionalId<Edge>) => { id: string; source: string; target: string; metadata: | ({ type: 'module-to-module' } & { sourceModuleName: string; targetModuleName: string; }) | ({ type: 'class-to-class'; sourceClassName: string; targetClassName: string; sourceClassToken: InjectionToken; targetClassToken: InjectionToken; injectionType: 'constructor' | 'property' | 'decorator'; keyOrIndex?: string | number | symbol; internal?: boolean; } & { sourceModuleName: string; targetModuleName: string });};method insertEntrypoint
insertEntrypoint: <T>(definition: Entrypoint<T>, parentId: string) => void;method insertNode
insertNode: (nodeDefinition: Node) => Node | undefined;method insertOrphanedEnhancer
insertOrphanedEnhancer: (entry: OrphanedEnhancerDefinition) => void;method toJSON
toJSON: () => SerializedGraphJson;method toString
toString: () => string;Interfaces
interface ContextId
interface ContextId {}interface ContextIdResolver
interface ContextIdResolver {}interface ContextIdStrategy
interface ContextIdStrategy<T = any> {}method attach
attach: ( contextId: ContextId, request: T) => ContextIdResolverFn | ContextIdResolver | undefined;Allows to attach a parent context id to the existing child context id. This lets you construct durable DI sub-trees that can be shared between contexts.
Parameter contextId
auto-generated child context id
Parameter request
request object
interface CreateDecoratorOptions
interface CreateDecoratorOptions<TParam = any, TTransformed = TParam> {}interface ExternalContextOptions
interface ExternalContextOptions {}property filters
filters?: boolean;property guards
guards?: boolean;property interceptors
interceptors?: boolean;interface FilterByInclude
interface FilterByInclude {}property include
include?: Function[];List of modules to include (whitelist) into the discovery process.
interface FilterByMetadataKey
interface FilterByMetadataKey {}property metadataKey
metadataKey?: string;A key to filter controllers and providers by. Only instance wrappers with the specified metadata key will be returned.
interface HostComponentInfo
interface HostComponentInfo {}property isTreeDurable
isTreeDurable: boolean;Flag that indicates whether DI subtree is durable
property token
token: InjectionToken;Injection token (or class reference)
interface ModuleRefGetOrResolveOpts
interface ModuleRefGetOrResolveOpts {}interface ParamsFactory
interface ParamsFactory {}method exchangeKeyForValue
exchangeKeyForValue: (type: number, data: ParamData, args: any) => any;interface ResolvedRoute
interface ResolvedRoute {}Final route description produced during the "collect" phase of the router pipeline and consumed during the "register" phase. Holds the fully composed path, the pre-built handler chain (proxy + host filter + optional version filter), and the metadata needed to register the route on the HTTP adapter and to insert an entrypoint into the graph inspector.
property controllerVersion
controllerVersion: VersionValue | undefined;property handler
handler: ResolvedRouteHandler;property host
host: string | RegExp | Array<string | RegExp> | undefined;property instanceWrapper
instanceWrapper: InstanceWrapper;property method
method: RequestMethod;property methodName
methodName: string;property methodVersion
methodVersion: VersionValue | undefined;property path
path: string;property rawPath
rawPath?: string;property targetCallback
targetCallback: RouterProxyCallback;property version
version: VersionValue | undefined;interface RouteConflict
interface RouteConflict {}interface RouteResolutionOptions
interface RouteResolutionOptions {}Options that control how
Resolver.resolvewalks the controller graph and registers routes on the HTTP adapter. Used internally to thread route-collection and deferred-registration concerns through the resolver chain without bloating individual method signatures.
property deferRegistration
deferRegistration?: boolean;When
true, the resolver still walks every controller and emitsonRouteResolvedcallbacks but skips the actual adapter registration step. The caller is then responsible for ordering and installing the collected routes viaregisterResolvedRoute. Defaults tofalse.
property onRouteResolved
onRouteResolved?: (route: ResolvedRoute) => void;Invoked once for each route after its final path, host and version have been composed. Lets the caller observe resolved routes (for conflict detection, specificity sorting, etc.) without coupling those concerns to the resolver itself.
Type Aliases
type ConflictKind
type ConflictKind = 'duplicate' | 'shadow';Distinguishes the two flavors of route overlap. -
duplicate— identical method + path + version + host registered twice. -shadow— patterns can match the same request but are not identical.
type ContextIdResolverFn
type ContextIdResolverFn = (info: HostComponentInfo) => ContextId;type DiscoverableDecorator
type DiscoverableDecorator<T> = ((opts?: T) => CustomDecorator) & { KEY: string;};type DiscoveryOptions
type DiscoveryOptions = FilterByInclude | FilterByMetadataKey;type IEntryNestModule
type IEntryNestModule = | Type<any> | DynamicModule | ForwardReference | Promise<IEntryNestModule>;Represents the entry (root) module type accepted by the NestFactory methods.
type ReflectableDecorator
type ReflectableDecorator<TParam, TTransformed = TParam> = (( opts?: TParam) => CustomDecorator) & { KEY: string;};type ResolvedRouteHandler
type ResolvedRouteHandler = (...args: unknown[]) => unknown;Loose callable signature shared by the various handler wrappers that are composed before adapter registration (host filter, version filter, request-scoped handler, etc.). They all accept the (req, res, next) trio but may be invoked variadically by adapter shims.
type Routes
type Routes = RouteTree[];type SerializedGraphStatus
type SerializedGraphStatus = 'partial' | 'complete';Package Files (33)
- adapters/http-adapter.d.ts
- application-config.d.ts
- constants.d.ts
- discovery/discovery-module.d.ts
- discovery/discovery-service.d.ts
- exceptions/base-exception-filter.d.ts
- helpers/context-id-factory.d.ts
- helpers/external-context-creator.d.ts
- helpers/http-adapter-host.d.ts
- index.d.ts
- injector/container.d.ts
- injector/inquirer/inquirer-constants.d.ts
- injector/instance-wrapper.d.ts
- injector/lazy-module-loader/lazy-module-loader.d.ts
- injector/module-ref.d.ts
- injector/modules-container.d.ts
- inspector/graph-inspector.d.ts
- inspector/initialize-on-preview.allowlist.d.ts
- inspector/partial-graph.host.d.ts
- inspector/serialized-graph.d.ts
- metadata-scanner.d.ts
- middleware/builder.d.ts
- nest-application-context.d.ts
- nest-application.d.ts
- nest-factory.d.ts
- repl/repl.d.ts
- router/interfaces/resolved-route.interface.d.ts
- router/interfaces/route-conflict.interface.d.ts
- router/interfaces/route-resolution-options.interface.d.ts
- router/interfaces/routes.interface.d.ts
- router/request/request-constants.d.ts
- router/router-module.d.ts
- services/reflector.service.d.ts
Dependencies (5)
Dev Dependencies (1)
Peer Dependencies (6)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@nestjs/core.
- Markdown[](https://www.jsdocs.io/package/@nestjs/core)
- HTML<a href="https://www.jsdocs.io/package/@nestjs/core"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5684 ms. - Missing or incorrect documentation? Open an issue for this package.
