@nestjs/common
- Version 8.4.7
- Published
- 367 kB
- 4 dependencies
- MIT license
Install
npm i @nestjs/common
yarn add @nestjs/common
pnpm add @nestjs/common
Overview
Nest - modern, fast, powerful node.js web framework (@common)
Index
Variables
Functions
- All()
- applyDecorators()
- assignMetadata()
- Bind()
- Body()
- CacheKey()
- CacheTTL()
- Catch()
- Controller()
- createParamDecorator()
- Delete()
- Dependencies()
- flatten()
- forwardRef()
- Get()
- Global()
- Head()
- Header()
- Headers()
- HostParam()
- HttpCode()
- Inject()
- Injectable()
- Ip()
- mixin()
- Module()
- Next()
- Optional()
- Options()
- Param()
- Patch()
- Post()
- Put()
- Query()
- Redirect()
- Render()
- Req()
- Request()
- RequestMapping()
- Res()
- Response()
- SerializeOptions()
- Session()
- SetMetadata()
- Sse()
- UploadedFile()
- UploadedFiles()
- UseFilters()
- UseGuards()
- UseInterceptors()
- UsePipes()
- Version()
Classes
ValidationPipe
- createExceptionFactory()
- errorHttpStatusCode
- exceptionFactory
- expectedType
- flattenValidationErrors()
- isDetailedOutputDisabled
- isPrimitive()
- isTransformEnabled
- loadTransformer()
- loadValidator()
- mapChildrenToValidationErrors()
- prependConstraintsWithParentProp()
- stripProtoKeys()
- toEmptyIfNil()
- toValidate()
- transform()
- transformOptions
- transformPrimitive()
- validate()
- validateCustomDecorators
- validatorOptions
Interfaces
HttpServer
- all()
- applyVersionFilter()
- close()
- createMiddlewareFactory()
- delete()
- enableCors()
- get()
- getHttpServer()
- getInstance()
- getRequestHostname()
- getRequestMethod()
- getRequestUrl()
- getType()
- head()
- init()
- initHttpServer()
- listen()
- options()
- patch()
- post()
- put()
- redirect()
- registerParserMiddleware()
- render()
- reply()
- setBaseViewsDir()
- setErrorHandler()
- setHeader()
- setNotFoundHandler()
- setViewEngine()
- status()
- use()
- useStaticAssets()
INestApplication
- close()
- connectMicroservice()
- enableCors()
- enableVersioning()
- getHttpAdapter()
- getHttpServer()
- getMicroservices()
- getUrl()
- listen()
- listenAsync()
- setGlobalPrefix()
- startAllMicroservices()
- startAllMicroservicesAsync()
- use()
- useGlobalFilters()
- useGlobalGuards()
- useGlobalInterceptors()
- useGlobalPipes()
- useWebSocketAdapter()
Enums
HttpStatus
- ACCEPTED
- AMBIGUOUS
- BAD_GATEWAY
- BAD_REQUEST
- CONFLICT
- CONTINUE
- CREATED
- EARLYHINTS
- EXPECTATION_FAILED
- FAILED_DEPENDENCY
- FORBIDDEN
- FOUND
- GATEWAY_TIMEOUT
- GONE
- HTTP_VERSION_NOT_SUPPORTED
- I_AM_A_TEAPOT
- INTERNAL_SERVER_ERROR
- LENGTH_REQUIRED
- METHOD_NOT_ALLOWED
- MISDIRECTED
- MOVED_PERMANENTLY
- NO_CONTENT
- NON_AUTHORITATIVE_INFORMATION
- NOT_ACCEPTABLE
- NOT_FOUND
- NOT_IMPLEMENTED
- NOT_MODIFIED
- OK
- PARTIAL_CONTENT
- PAYLOAD_TOO_LARGE
- PAYMENT_REQUIRED
- PERMANENT_REDIRECT
- PRECONDITION_FAILED
- PRECONDITION_REQUIRED
- PROCESSING
- PROXY_AUTHENTICATION_REQUIRED
- REQUEST_TIMEOUT
- REQUESTED_RANGE_NOT_SATISFIABLE
- RESET_CONTENT
- SEE_OTHER
- SERVICE_UNAVAILABLE
- SWITCHING_PROTOCOLS
- TEMPORARY_REDIRECT
- TOO_MANY_REQUESTS
- UNAUTHORIZED
- UNPROCESSABLE_ENTITY
- UNSUPPORTED_MEDIA_TYPE
- URI_TOO_LONG
Type Aliases
Variables
variable CACHE_KEY_METADATA
const CACHE_KEY_METADATA: string;
variable CACHE_MANAGER
const CACHE_MANAGER: string;
variable CACHE_MODULE_OPTIONS
const CACHE_MODULE_OPTIONS: string;
variable CACHE_TTL_METADATA
const CACHE_TTL_METADATA: string;
variable VERSION_NEUTRAL
const VERSION_NEUTRAL: Symbol;
Indicates that this will work for any version passed in the request, or no version.
Functions
function All
All: (path?: string | string[]) => MethodDecorator;
Route handler (method) Decorator. Routes all HTTP requests to the specified path.
See Also
[Routing](https://docs.nestjs.com/controllers#routing)
function applyDecorators
applyDecorators: ( ...decorators: Array<ClassDecorator | MethodDecorator | PropertyDecorator>) => <TFunction extends Function, Y>( target: object | TFunction, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
Function that returns a new decorator that applies all decorators provided by param
Useful to build new decorators (or a decorator factory) encapsulating multiple decorators related with the same feature
Parameter decorators
one or more decorators (e.g.,
ApplyGuard(...)
)
function assignMetadata
assignMetadata: <TParamtype = any, TArgs = any>( args: TArgs, paramtype: TParamtype, index: number, data?: ParamData, ...pipes: (Type<PipeTransform> | PipeTransform)[]) => TArgs & { [x: string]: { index: number; data: ParamData; pipes: (PipeTransform<any, any> | Type<PipeTransform<any, any>>)[]; };};
function Bind
Bind: (...decorators: any[]) => MethodDecorator;
Decorator that binds *parameter decorators* to the method that follows.
Useful when the language doesn't provide a 'Parameter Decorator' feature (i.e., vanilla JavaScript).
Parameter decorators
one or more parameter decorators (e.g.,
Req()
)
function Body
Body: { (): ParameterDecorator; ( ...pipes: (PipeTransform<any, any> | Type<PipeTransform<any, any>>)[] ): ParameterDecorator; ( property: string, ...pipes: (PipeTransform<any, any> | Type<PipeTransform<any, any>>)[] ): ParameterDecorator;};
Route handler parameter decorator. Extracts the entire
body
object from thereq
object and populates the decorated parameter with the value ofbody
.For example:
async create(@Body() createDto: CreateCatDto)See Also
[Request object](https://docs.nestjs.com/controllers#request-object)
Route handler parameter decorator. Extracts the entire
body
object from thereq
object and populates the decorated parameter with the value ofbody
. Also applies the specified pipes to that parameter.For example:
async create(@Body(new ValidationPipe()) createDto: CreateCatDto)Parameter pipes
one or more pipes - either instances or classes - to apply to the bound body parameter.
See Also
[Request object](https://docs.nestjs.com/controllers#request-object)
[Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes)
Route handler parameter decorator. Extracts a single property from the
body
object property of thereq
object and populates the decorated parameter with the value of that property. Also applies pipes to the bound body parameter.For example:
async create(@Body('role', new ValidationPipe()) role: string)Parameter property
name of single property to extract from the
body
objectParameter pipes
one or more pipes - either instances or classes - to apply to the bound body parameter.
See Also
[Request object](https://docs.nestjs.com/controllers#request-object)
[Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes)
function CacheKey
CacheKey: (key: string) => import('../../decorators').CustomDecorator<string>;
Decorator that sets the caching key used to store/retrieve cached items for Web sockets or Microservice based apps.
For example:
@CacheKey('events')
Parameter key
string naming the field to be used as a cache key
See Also
[Caching](https://docs.nestjs.com/techniques/caching)
function CacheTTL
CacheTTL: ( ttl: number | CacheTTLFactory) => import('../../decorators').CustomDecorator<string>;
function Catch
Catch: (...exceptions: Array<Type<any> | Abstract<any>>) => ClassDecorator;
Decorator that marks a class as a Nest exception filter. An exception filter handles exceptions thrown by or not handled by your application code.
The decorated class must implement the
ExceptionFilter
interface.Parameter exceptions
one or more exception *types* specifying the exceptions to be caught and handled by this filter.
See Also
[Exception Filters](https://docs.nestjs.com/exception-filters)
Exception filters are applied using the
@UseFilters()
decorator, or (globally) withapp.useGlobalFilters()
.
function Controller
Controller: { (): ClassDecorator; (prefix: string | string[]): ClassDecorator; (options: ControllerOptions): ClassDecorator;};
Decorator that marks a class as a Nest controller that can receive inbound requests and produce responses.
An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. It defines a class that provides the context for one or more related route handlers that correspond to HTTP request methods and associated routes for example
GET /api/profile
,POST /users/resume
.A Microservice Controller responds to requests as well as events, running over a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). It defines a class that provides a context for one or more message or event handlers.
See Also
[Controllers](https://docs.nestjs.com/controllers)
[Microservices](https://docs.nestjs.com/microservices/basics#request-response)
Decorator that marks a class as a Nest controller that can receive inbound requests and produce responses.
An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. It defines a class that provides the context for one or more related route handlers that correspond to HTTP request methods and associated routes for example
GET /api/profile
,POST /users/resume
.A Microservice Controller responds to requests as well as events, running over a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). It defines a class that provides a context for one or more message or event handlers.
Parameter prefix
string that defines a
route path prefix
. The prefix is pre-pended to the path specified in any request decorator in the class.See Also
[Routing](https://docs.nestjs.com/controllers#routing)
[Controllers](https://docs.nestjs.com/controllers)
[Microservices](https://docs.nestjs.com/microservices/basics#request-response)
Decorator that marks a class as a Nest controller that can receive inbound requests and produce responses.
An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. It defines a class that provides the context for one or more related route handlers that correspond to HTTP request methods and associated routes for example
GET /api/profile
,POST /users/resume
.A Microservice Controller responds to requests as well as events, running over a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). It defines a class that provides a context for one or more message or event handlers.
Parameter options
configuration object specifying:
-
scope
- symbol that determines the lifetime of a Controller instance. [See Scope](https://docs.nestjs.com/fundamentals/injection-scopes#usage) for more details. -prefix
- string that defines aroute path prefix
. The prefix is pre-pended to the path specified in any request decorator in the class. -version
- string, array of strings, or Symbol that defines the version of all routes in the class. [See Versioning](https://docs.nestjs.com/techniques/versioning) for more details.See Also
[Routing](https://docs.nestjs.com/controllers#routing)
[Controllers](https://docs.nestjs.com/controllers)
[Microservices](https://docs.nestjs.com/microservices/basics#request-response)
[Versioning](https://docs.nestjs.com/techniques/versioning)
function createParamDecorator
createParamDecorator: < FactoryData = any, FactoryInput = any, FactoryOutput = any>( factory: CustomParamFactory<FactoryData, FactoryInput, FactoryOutput>, enhancers?: ParamDecoratorEnhancer[]) => ( ...dataOrPipes: (Type<PipeTransform> | PipeTransform | FactoryData)[]) => ParameterDecorator;
Defines HTTP route param decorator
Parameter factory
function Delete
Delete: (path?: string | string[]) => MethodDecorator;
Route handler (method) Decorator. Routes HTTP DELETE requests to the specified path.
See Also
[Routing](https://docs.nestjs.com/controllers#routing)
function Dependencies
Dependencies: (...dependencies: Array<unknown>) => ClassDecorator;
Decorator that sets required dependencies (required with a vanilla JavaScript objects)
function flatten
flatten: <T extends unknown[] = any>( arr: T) => T extends (infer R)[] ? R : never;
function forwardRef
forwardRef: (fn: () => any) => ForwardReference;
function Get
Get: (path?: string | string[]) => MethodDecorator;
Route handler (method) Decorator. Routes HTTP GET requests to the specified path.
See Also
[Routing](https://docs.nestjs.com/controllers#routing)
function Global
Global: () => ClassDecorator;
Decorator that makes a module global-scoped.
Once imported into any module, a global-scoped module will be visible in all modules. Thereafter, modules that wish to inject a service exported from a global module do not need to import the provider module.
See Also
[Global modules](https://docs.nestjs.com/modules#global-modules)
function Head
Head: (path?: string | string[]) => MethodDecorator;
Route handler (method) Decorator. Routes HTTP HEAD requests to the specified path.
See Also
[Routing](https://docs.nestjs.com/controllers#routing)
function Header
Header: (name: string, value: string) => MethodDecorator;
Request method Decorator. Sets a response header.
For example:
@Header('Cache-Control', 'none')
Parameter name
string to be used for header name
Parameter value
string to be used for header value
See Also
[Headers](https://docs.nestjs.com/controllers#headers)
function Headers
Headers: (property?: string) => ParameterDecorator;
Route handler parameter decorator. Extracts the
headers
property from thereq
object and populates the decorated parameter with the value ofheaders
.For example:
async update(@Headers('Cache-Control') cacheControl: string)
Parameter property
name of single header property to extract.
See Also
[Request object](https://docs.nestjs.com/controllers#request-object)
function HostParam
HostParam: { (): ParameterDecorator; (property: string): ParameterDecorator };
Route handler parameter decorator. Extracts the
hosts
property from thereq
object and populates the decorated parameter with the value ofhosts
. May also apply pipes to the bound parameter.For example, extracting all params:
findOne(@HostParam() params: string[])For example, extracting a single param:
findOne(@HostParam('id') id: string)Parameter property
name of single property to extract from the
req
objectSee Also
[Request object](https://docs.nestjs.com/controllers#request-object)
function HttpCode
HttpCode: (statusCode: number) => MethodDecorator;
Request method Decorator. Defines the HTTP response status code. Overrides default status code for the decorated request method.
Parameter statusCode
HTTP response code to be returned by route handler.
See Also
[Http Status Codes](https://docs.nestjs.com/controllers#status-code)
function Inject
Inject: <T = any>( token?: T) => (target: object, key: string | symbol, index?: number) => void;
Decorator that marks a constructor parameter as a target for [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection).
Any injected provider must be visible within the module scope (loosely speaking, the containing module) of the class it is being injected into. This can be done by:
- defining the provider in the same module scope - exporting the provider from one module scope and importing that module into the module scope of the class being injected into - exporting the provider from a module that is marked as global using the
@Global()
decorator#### Injection tokens Can be *types* (class names), *strings* or *symbols*. This depends on how the provider with which it is associated was defined. Providers defined with the
@Injectable()
decorator use the class name. Custom Providers may use strings or symbols as the injection token.Parameter token
lookup key for the provider to be injected (assigned to the constructor parameter).
See Also
[Providers](https://docs.nestjs.com/providers)
[Custom Providers](https://docs.nestjs.com/fundamentals/custom-providers)
[Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes)
function Injectable
Injectable: (options?: InjectableOptions) => ClassDecorator;
Decorator that marks a class as a [provider](https://docs.nestjs.com/providers). Providers can be injected into other classes via constructor parameter injection using Nest's built-in [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection) system.
When injecting a provider, it must be visible within the module scope (loosely speaking, the containing module) of the class it is being injected into. This can be done by:
- defining the provider in the same module scope - exporting the provider from one module scope and importing that module into the module scope of the class being injected into - exporting the provider from a module that is marked as global using the
@Global()
decoratorProviders can also be defined in a more explicit and imperative form using various [custom provider](https://docs.nestjs.com/fundamentals/custom-providers) techniques that expose more capabilities of the DI system.
Parameter options
options specifying scope of injectable
See Also
[Providers](https://docs.nestjs.com/providers)
[Custom Providers](https://docs.nestjs.com/fundamentals/custom-providers)
[Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes)
function Ip
Ip: () => ParameterDecorator;
Route handler parameter decorator. Extracts the
Ip
property from thereq
object and populates the decorated parameter with the value ofip
.See Also
[Request object](https://docs.nestjs.com/controllers#request-object)
function mixin
mixin: <T>(mixinClass: Type<T>) => Type<T>;
function Module
Module: (metadata: ModuleMetadata) => ClassDecorator;
Decorator that marks a class as a [module](https://docs.nestjs.com/modules).
Modules are used by Nest to organize the application structure into scopes. Controllers and Providers are scoped by the module they are declared in. Modules and their classes (Controllers and Providers) form a graph that determines how Nest performs [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection).
Parameter metadata
module configuration metadata
See Also
[Modules](https://docs.nestjs.com/modules)
function Next
Next: () => ParameterDecorator;
Route handler parameter decorator. Extracts reference to the
Next
function from the underlying platform and populates the decorated parameter with the value ofNext
.
function Optional
Optional: () => (target: object, key: string | symbol, index?: number) => void;
Parameter decorator for an injected dependency marking the dependency as optional.
For example:
constructor(@Optional() @Inject('HTTP_OPTIONS')private readonly httpClient: T) {}See Also
[Optional providers](https://docs.nestjs.com/providers#optional-providers)
function Options
Options: (path?: string | string[]) => MethodDecorator;
Route handler (method) Decorator. Routes HTTP OPTIONS requests to the specified path.
See Also
[Routing](https://docs.nestjs.com/controllers#routing)
function Param
Param: { (): ParameterDecorator; ( ...pipes: (PipeTransform<any, any> | Type<PipeTransform<any, any>>)[] ): ParameterDecorator; ( property: string, ...pipes: (PipeTransform<any, any> | Type<PipeTransform<any, any>>)[] ): ParameterDecorator;};
Route handler parameter decorator. Extracts the
params
property from thereq
object and populates the decorated parameter with the value ofparams
. May also apply pipes to the bound parameter.For example, extracting all params:
findOne(@Param() params: string[])For example, extracting a single param:
findOne(@Param('id') id: string)Parameter property
name of single property to extract from the
req
objectParameter pipes
one or more pipes - either instances or classes - to apply to the bound parameter.
See Also
[Request object](https://docs.nestjs.com/controllers#request-object)
[Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes)
function Patch
Patch: (path?: string | string[]) => MethodDecorator;
Route handler (method) Decorator. Routes HTTP PATCH requests to the specified path.
See Also
[Routing](https://docs.nestjs.com/controllers#routing)
function Post
Post: (path?: string | string[]) => MethodDecorator;
Route handler (method) Decorator. Routes HTTP POST requests to the specified path.
See Also
[Routing](https://docs.nestjs.com/controllers#routing)
function Put
Put: (path?: string | string[]) => MethodDecorator;
Route handler (method) Decorator. Routes HTTP PUT requests to the specified path.
See Also
[Routing](https://docs.nestjs.com/controllers#routing)
function Query
Query: { (): ParameterDecorator; ( ...pipes: (PipeTransform<any, any> | Type<PipeTransform<any, any>>)[] ): ParameterDecorator; ( property: string, ...pipes: (PipeTransform<any, any> | Type<PipeTransform<any, any>>)[] ): ParameterDecorator;};
Route handler parameter decorator. Extracts the
query
property from thereq
object and populates the decorated parameter with the value ofquery
. May also apply pipes to the bound query parameter.For example:
async find(@Query('user') user: string)Parameter property
name of single property to extract from the
query
objectParameter pipes
one or more pipes to apply to the bound query parameter
See Also
[Request object](https://docs.nestjs.com/controllers#request-object)
function Redirect
Redirect: (url?: string, statusCode?: number) => MethodDecorator;
Redirects request to the specified URL.
function Render
Render: (template: string) => MethodDecorator;
Route handler method Decorator. Defines a template to be rendered by the controller.
For example:
@Render('index')
Parameter template
name of the render engine template file
See Also
[Model-View-Controller](https://docs.nestjs.com/techniques/mvc)
function Req
Req: () => ParameterDecorator;
function Request
Request: () => ParameterDecorator;
Route handler parameter decorator. Extracts the
Request
object from the underlying platform and populates the decorated parameter with the value ofRequest
.Example:
logout(@Request() req)
See Also
[Request object](https://docs.nestjs.com/controllers#request-object)
function RequestMapping
RequestMapping: (metadata?: RequestMappingMetadata) => MethodDecorator;
function Res
Res: (options?: ResponseDecoratorOptions) => ParameterDecorator;
function Response
Response: (options?: ResponseDecoratorOptions) => ParameterDecorator;
Route handler parameter decorator. Extracts the
Response
object from the underlying platform and populates the decorated parameter with the value ofResponse
.Example:
logout(@Response() res)
function SerializeOptions
SerializeOptions: ( options: ClassTransformOptions) => import('../../decorators').CustomDecorator<string>;
function Session
Session: () => ParameterDecorator;
Route handler parameter decorator. Extracts the
Session
object from the underlying platform and populates the decorated parameter with the value ofSession
.See Also
[Request object](https://docs.nestjs.com/controllers#request-object)
function SetMetadata
SetMetadata: <K = string, V = any>( metadataKey: K, metadataValue: V) => CustomDecorator<K>;
Decorator that assigns metadata to the class/function using the specified
key
.Requires two parameters: -
key
- a value defining the key under which the metadata is stored -value
- metadata to be associated withkey
This metadata can be reflected using the
Reflector
class.Example:
@SetMetadata('roles', ['admin'])
See Also
[Reflection](https://docs.nestjs.com/guards#reflection)
function Sse
Sse: (path?: string) => MethodDecorator;
Declares this route as a Server-Sent-Events endpoint
function UploadedFile
UploadedFile: { (): ParameterDecorator; ( ...pipes: (PipeTransform<any, any> | Type<PipeTransform<any, any>>)[] ): ParameterDecorator; ( fileKey?: string, ...pipes: (PipeTransform<any, any> | Type<PipeTransform<any, any>>)[] ): ParameterDecorator;};
Route handler parameter decorator. Extracts the
file
object and populates the decorated parameter with the value offile
. Used in conjunction with [multer middleware](https://github.com/expressjs/multer) for Express-based applications.For example:
uploadFile(@UploadedFile() file) {console.log(file);}See Also
[Request object](https://docs.nestjs.com/techniques/file-upload)
function UploadedFiles
UploadedFiles: { (): ParameterDecorator; ( ...pipes: (PipeTransform<any, any> | Type<PipeTransform<any, any>>)[] ): ParameterDecorator;};
Route handler parameter decorator. Extracts the
files
object and populates the decorated parameter with the value offiles
. Used in conjunction with [multer middleware](https://github.com/expressjs/multer) for Express-based applications.For example:
uploadFile(@UploadedFiles() files) {console.log(files);}See Also
[Request object](https://docs.nestjs.com/techniques/file-upload)
function UseFilters
UseFilters: ( ...filters: (ExceptionFilter | Function)[]) => MethodDecorator & ClassDecorator;
Decorator that binds exception filters to the scope of the controller or method, depending on its context.
When
@UseFilters
is used at the controller level, the filter will be applied to every handler (method) in the controller.When
@UseFilters
is used at the individual handler level, the filter will apply only to that specific method.Parameter filters
exception filter instance or class, or a list of exception filter instances or classes.
See Also
[Exception filters](https://docs.nestjs.com/exception-filters)
Exception filters can also be set up globally for all controllers and routes using
app.useGlobalFilters()
. [See here for details](https://docs.nestjs.com/exception-filters#binding-filters)
function UseGuards
UseGuards: ( ...guards: (CanActivate | Function)[]) => MethodDecorator & ClassDecorator;
Decorator that binds guards to the scope of the controller or method, depending on its context.
When
@UseGuards
is used at the controller level, the guard will be applied to every handler (method) in the controller.When
@UseGuards
is used at the individual handler level, the guard will apply only to that specific method.Parameter guards
a single guard instance or class, or a list of guard instances or classes.
See Also
[Guards](https://docs.nestjs.com/guards)
Guards can also be set up globally for all controllers and routes using
app.useGlobalGuards()
. [See here for details](https://docs.nestjs.com/guards#binding-guards)
function UseInterceptors
UseInterceptors: ( ...interceptors: (NestInterceptor | Function)[]) => MethodDecorator & ClassDecorator;
Decorator that binds interceptors to the scope of the controller or method, depending on its context.
When
@UseInterceptors
is used at the controller level, the interceptor will be applied to every handler (method) in the controller.When
@UseInterceptors
is used at the individual handler level, the interceptor will apply only to that specific method.Parameter interceptors
a single interceptor instance or class, or a list of interceptor instances or classes.
See Also
[Interceptors](https://docs.nestjs.com/interceptors)
Interceptors can also be set up globally for all controllers and routes using
app.useGlobalInterceptors()
. [See here for details](https://docs.nestjs.com/interceptors#binding-interceptors)
function UsePipes
UsePipes: ( ...pipes: (PipeTransform | Function)[]) => ClassDecorator & MethodDecorator;
Decorator that binds pipes to the scope of the controller or method, depending on its context.
When
@UsePipes
is used at the controller level, the pipe will be applied to every handler (method) in the controller.When
@UsePipes
is used at the individual handler level, the pipe will apply only to that specific method.Parameter pipes
a single pipe instance or class, or a list of pipe instances or classes.
See Also
[Pipes](https://docs.nestjs.com/pipes)
Pipes can also be set up globally for all controllers and routes using
app.useGlobalPipes()
. [See here for details](https://docs.nestjs.com/pipes#class-validator)
function Version
Version: (version: VersionValue) => MethodDecorator;
Sets the version of the endpoint to the passed version
Classes
class BadGatewayException
class BadGatewayException extends HttpException {}
Defines an HTTP exception for *Bad Gateway* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
BadGatewayException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new BadGatewayException()
The HTTP response status code will be 502. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 502. -message
: the string'Bad Gateway'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class BadRequestException
class BadRequestException extends HttpException {}
Defines an HTTP exception for *Bad Request* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
BadRequestException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new BadRequestException()
The HTTP response status code will be 400. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 400. -message
: the string'Bad Request'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class CacheInterceptor
class CacheInterceptor implements NestInterceptor {}
constructor
constructor(cacheManager: any, reflector: any);
property allowedMethods
protected allowedMethods: string[];
property cacheManager
protected readonly cacheManager: any;
property httpAdapterHost
protected readonly httpAdapterHost: HttpAdapterHost<any>;
property reflector
protected readonly reflector: any;
method intercept
intercept: ( context: ExecutionContext, next: CallHandler) => Promise<Observable<any>>;
method isRequestCacheable
protected isRequestCacheable: (context: ExecutionContext) => boolean;
method trackBy
protected trackBy: (context: ExecutionContext) => string | undefined;
class CacheModule
class CacheModule {}
Module that provides Nest cache-manager.
See Also
[Caching](https://docs.nestjs.com/techniques/caching)
method register
static register: <StoreConfig extends Record<any, any> = Record<string, any>>( options?: CacheModuleOptions<StoreConfig>) => DynamicModule;
Configure the cache manager statically.
Parameter options
options to configure the cache manager
See Also
[Customize caching](https://docs.nestjs.com/techniques/caching#customize-caching)
method registerAsync
static registerAsync: < StoreConfig extends Record<any, any> = Record<string, any>>( options: CacheModuleAsyncOptions<StoreConfig>) => DynamicModule;
Configure the cache manager dynamically.
Parameter options
method for dynamically supplying cache manager configuration options
See Also
[Async configuration](https://docs.nestjs.com/techniques/caching#async-configuration)
class ClassSerializerInterceptor
class ClassSerializerInterceptor implements NestInterceptor {}
constructor
constructor(reflector: any, defaultOptions?: ClassSerializerInterceptorOptions);
property defaultOptions
protected readonly defaultOptions: ClassSerializerInterceptorOptions;
property reflector
protected readonly reflector: any;
method getContextOptions
protected getContextOptions: ( context: ExecutionContext) => ClassTransformOptions | undefined;
method intercept
intercept: (context: ExecutionContext, next: CallHandler) => Observable<any>;
method serialize
serialize: ( response: PlainLiteralObject | Array<PlainLiteralObject>, options: ClassTransformOptions) => PlainLiteralObject | Array<PlainLiteralObject>;
Serializes responses that are non-null objects nor streamable files.
method transformToPlain
transformToPlain: ( plainOrClass: any, options: ClassTransformOptions) => PlainLiteralObject;
class ConflictException
class ConflictException extends HttpException {}
Defines an HTTP exception for *Conflict* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
ConflictException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new ConflictException()
The HTTP response status code will be 409. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 409. -message
: the string'Conflict'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class ConsoleLogger
class ConsoleLogger implements LoggerService {}
constructor
constructor();
constructor
constructor(context: string);
constructor
constructor(context: string, options: ConsoleLoggerOptions);
property context
protected context?: string;
property options
protected options: ConsoleLoggerOptions;
method colorize
protected colorize: (message: string, logLevel: LogLevel) => string;
method debug
debug: { (message: any, context?: string): void; (message: any, ...optionalParams: any[]): void;};
Write a 'debug' level log, if the configured level allows for it. Prints to
stdout
with newline.
method error
error: { (message: any, stack?: string, context?: string): void; (message: any, ...optionalParams: any[]): void;};
Write an 'error' level log, if the configured level allows for it. Prints to
stderr
with newline.
method formatMessage
protected formatMessage: ( logLevel: LogLevel, message: unknown, pidMessage: string, formattedLogLevel: string, contextMessage: string, timestampDiff: string) => string;
method formatPid
protected formatPid: (pid: number) => string;
method getTimestamp
protected getTimestamp: () => string;
method isLevelEnabled
isLevelEnabled: (level: LogLevel) => boolean;
method log
log: { (message: any, context?: string): void; (message: any, ...optionalParams: any[]): void;};
Write a 'log' level log, if the configured level allows for it. Prints to
stdout
with newline.
method printMessages
protected printMessages: ( messages: unknown[], context?: string, logLevel?: LogLevel, writeStreamType?: 'stdout' | 'stderr') => void;
method printStackTrace
protected printStackTrace: (stack: string) => void;
method resetContext
resetContext: () => void;
Resets the logger context to the value that was passed in the constructor.
method setContext
setContext: (context: string) => void;
Set logger context
Parameter context
context
method setLogLevels
setLogLevels: (levels: LogLevel[]) => void;
Set log levels
Parameter levels
log levels
method stringifyMessage
protected stringifyMessage: (message: unknown, logLevel: LogLevel) => string;
method verbose
verbose: { (message: any, context?: string): void; (message: any, ...optionalParams: any[]): void;};
Write a 'verbose' level log, if the configured level allows for it. Prints to
stdout
with newline.
method warn
warn: { (message: any, context?: string): void; (message: any, ...optionalParams: any[]): void;};
Write a 'warn' level log, if the configured level allows for it. Prints to
stdout
with newline.
class DefaultValuePipe
class DefaultValuePipe<T = any, R = any> implements PipeTransform<T, T | R> {}
Defines the built-in DefaultValue Pipe
See Also
[Built-in Pipes](https://docs.nestjs.com/pipes#built-in-pipes)
constructor
constructor(defaultValue: {});
property defaultValue
protected readonly defaultValue: {};
method transform
transform: (value?: T, _metadata?: ArgumentMetadata) => T | R;
class ForbiddenException
class ForbiddenException extends HttpException {}
Defines an HTTP exception for *Forbidden* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
ForbiddenException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new ForbiddenException()
The HTTP response status code will be 403. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 403. -message
: the string'Forbidden'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class GatewayTimeoutException
class GatewayTimeoutException extends HttpException {}
Defines an HTTP exception for *Gateway Timeout* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
GatewayTimeoutException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new GatewayTimeoutException()
The HTTP response status code will be 504. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 504. -message
: the string'Gateway Timeout'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class GoneException
class GoneException extends HttpException {}
Defines an HTTP exception for *Gone* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
GoneException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new GoneException()
The HTTP response status code will be 410. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 410. -message
: the string'Gone'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class HttpException
class HttpException extends Error {}
Defines the base Nest HTTP exception, which is handled by the default Exceptions Handler.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(response: string | Record<string, any>, status: number);
Instantiate a plain HTTP Exception.
Parameter response
string or object describing the error condition.
Parameter status
HTTP response status code.
Example 1
throw new HttpException()
The constructor arguments define the response and the HTTP response status code. - The
response
argument (required) defines the JSON response body. - Thestatus
argument (required) defines the HTTP Status Code.By default, the JSON response body contains two properties: -
statusCode
: the Http Status Code. -message
: a short description of the HTTP error by default; override this by supplying a string in theresponse
parameter.To override the entire JSON response body, pass an object to the
createBody
method. Nest will serialize the object and return it as the JSON response body.The
status
argument is required, and should be a valid HTTP status code. Best practice is to use theHttpStatus
enum imported fromnestjs/common
.
method createBody
static createBody: ( objectOrError: object | string, description?: string, statusCode?: number) => object;
method getResponse
getResponse: () => string | object;
method getStatus
getStatus: () => number;
method initMessage
initMessage: () => void;
method initName
initName: () => void;
class HttpModule
class HttpModule {}
Deprecated
"HttpModule" (from the "@nestjs/common" package) is deprecated and will be removed in the next major release. Please, use the "@nestjs/axios" package instead.
method register
static register: (config: AxiosRequestConfig) => DynamicModule;
method registerAsync
static registerAsync: (options: HttpModuleAsyncOptions) => DynamicModule;
class HttpService
class HttpService {}
Deprecated
"HttpModule" (from the "@nestjs/common" package) is deprecated and will be removed in the next major release. Please, use the "@nestjs/axios" package instead.
constructor
constructor(instance?: AxiosInstance);
property axiosRef
readonly axiosRef: AxiosInstance;
method delete
delete: <T = any>( url: string, config?: AxiosRequestConfig) => Observable<AxiosResponse<T>>;
method get
get: <T = any>( url: string, config?: AxiosRequestConfig) => Observable<AxiosResponse<T>>;
method head
head: <T = any>( url: string, config?: AxiosRequestConfig) => Observable<AxiosResponse<T>>;
method patch
patch: <T = any>( url: string, data?: any, config?: AxiosRequestConfig) => Observable<AxiosResponse<T>>;
method post
post: <T = any>( url: string, data?: any, config?: AxiosRequestConfig) => Observable<AxiosResponse<T>>;
method put
put: <T = any>( url: string, data?: any, config?: AxiosRequestConfig) => Observable<AxiosResponse<T>>;
method request
request: <T = any>(config: AxiosRequestConfig) => Observable<AxiosResponse<T>>;
class HttpVersionNotSupportedException
class HttpVersionNotSupportedException extends HttpException {}
Defines an HTTP exception for *Http Version Not Supported* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
HttpVersionNotSupportedException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new HttpVersionNotSupportedException()
The HTTP response status code will be 505. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 505. -message
: the string'HTTP Version Not Supported'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class ImATeapotException
class ImATeapotException extends HttpException {}
Defines an HTTP exception for *ImATeapotException* type errors.
Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate an
ImATeapotException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new ImATeapotException()
The HTTP response status code will be 418. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 418. -message
: the string"I'm a Teapot"
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class InternalServerErrorException
class InternalServerErrorException extends HttpException {}
Defines an HTTP exception for *Internal Server Error* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate an
InternalServerErrorException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new InternalServerErrorException()
The HTTP response status code will be 500. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 500. -message
: the string'Internal Server Error'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class Logger
class Logger implements LoggerService {}
constructor
constructor();
constructor
constructor(context: string);
constructor
constructor(context: string, options?: { timestamp?: boolean });
property context
protected context?: string;
property localInstance
readonly localInstance: LoggerService;
property localInstanceRef
protected localInstanceRef?: LoggerService;
property logBuffer
protected static logBuffer: LogBufferRecord[];
property logLevels
protected static logLevels?: LogLevel[];
property options
protected options: { timestamp?: boolean };
property staticInstanceRef
protected static staticInstanceRef?: LoggerService;
method attachBuffer
static attachBuffer: () => void;
Attach buffer. Turns on initialisation logs buffering.
method debug
static debug: { (message: any, context?: string): void; (message: any, ...optionalParams: any[]): void;};
Write a 'debug' level log.
Write a 'debug' level log, if the configured level allows for it. Prints to
stdout
with newline.
method detachBuffer
static detachBuffer: () => void;
Detach buffer. Turns off initialisation logs buffering.
method error
static error: { (message: any, context?: string): void; (message: any, stack?: string, context?: string): void; (message: any, ...optionalParams: any[]): void;};
Write an 'error' level log.
method flush
static flush: () => void;
Print buffered logs and detach buffer.
method getTimestamp
static getTimestamp: () => string;
method isLevelEnabled
static isLevelEnabled: (level: LogLevel) => boolean;
method log
static log: { (message: any, context?: string): void; (message: any, ...optionalParams: any[]): void;};
Write a 'log' level log.
method overrideLogger
static overrideLogger: (logger: LoggerService | LogLevel[] | boolean) => any;
method verbose
static verbose: { (message: any, context?: string): void; (message: any, ...optionalParams: any[]): void;};
Write a 'verbose' level log.
method warn
static warn: { (message: any, context?: string): void; (message: any, ...optionalParams: any[]): void;};
Write a 'warn' level log.
class MethodNotAllowedException
class MethodNotAllowedException extends HttpException {}
Defines an HTTP exception for *Method Not Allowed* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
MethodNotAllowedException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new MethodNotAllowedException()
The HTTP response status code will be 405. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 405. -message
: the string'Method Not Allowed'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class MisdirectedException
class MisdirectedException extends HttpException {}
Defines an HTTP exception for *Misdirected* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
MisdirectedException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new MisdirectedException()
The HTTP response status code will be 421. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 421. -message
: the string'Bad Gateway'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class NotAcceptableException
class NotAcceptableException extends HttpException {}
Defines an HTTP exception for *Not Acceptable* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
NotAcceptableException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new NotAcceptableException()
The HTTP response status code will be 406. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 406. -error
: the string'Not Acceptable'
by default; override this by supplying a string in theerror
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class NotFoundException
class NotFoundException extends HttpException {}
Defines an HTTP exception for *Not Found* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
NotFoundException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new NotFoundException()
The HTTP response status code will be 404. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 404. -message
: the string'Not Found'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class NotImplementedException
class NotImplementedException extends HttpException {}
Defines an HTTP exception for *Not Implemented* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
NotImplementedException
Exception.Parameter description
string or object describing the error condition.
Parameter error
a short description of the HTTP error.
Example 1
throw new NotImplementedException()
The HTTP response status code will be 501. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 501. -message
: the string'Not Implemented'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class ParseArrayPipe
class ParseArrayPipe implements PipeTransform {}
Defines the built-in ParseArray Pipe
See Also
[Built-in Pipes](https://docs.nestjs.com/pipes#built-in-pipes)
constructor
constructor(options?: ParseArrayOptions);
property exceptionFactory
protected exceptionFactory: (error: string) => any;
property options
protected readonly options: ParseArrayOptions;
property validationPipe
protected readonly validationPipe: ValidationPipe;
method isExpectedTypePrimitive
protected isExpectedTypePrimitive: () => boolean;
method transform
transform: (value: any, metadata: ArgumentMetadata) => Promise<any>;
Method that accesses and performs optional transformation on argument for in-flight requests.
Parameter value
currently processed route argument
Parameter metadata
contains metadata about the currently processed route argument
method validatePrimitive
protected validatePrimitive: (originalValue: any, index?: number) => any;
class ParseBoolPipe
class ParseBoolPipe implements PipeTransform<string | boolean, Promise<boolean>> {}
Defines the built-in ParseBool Pipe
See Also
[Built-in Pipes](https://docs.nestjs.com/pipes#built-in-pipes)
constructor
constructor(options?: ParseBoolPipeOptions);
property exceptionFactory
protected exceptionFactory: (error: string) => any;
method isFalse
protected isFalse: (value: string | boolean) => boolean;
Parameter value
currently processed route argument
Returns
true
ifvalue
is said 'false', ie., if it is equal to the booleanfalse
or the string"false"
method isTrue
protected isTrue: (value: string | boolean) => boolean;
Parameter value
currently processed route argument
Returns
true
ifvalue
is said 'true', ie., if it is equal to the booleantrue
or the string"true"
method transform
transform: ( value: string | boolean, metadata: ArgumentMetadata) => Promise<boolean>;
Method that accesses and performs optional transformation on argument for in-flight requests.
Parameter value
currently processed route argument
Parameter metadata
contains metadata about the currently processed route argument
class ParseEnumPipe
class ParseEnumPipe<T = any> implements PipeTransform<T> {}
Defines the built-in ParseEnum Pipe
See Also
[Built-in Pipes](https://docs.nestjs.com/pipes#built-in-pipes)
constructor
constructor(enumType: {}, options?: ParseEnumPipeOptions);
property enumType
protected readonly enumType: {};
property exceptionFactory
protected exceptionFactory: (error: string) => any;
method isEnum
protected isEnum: (value: T) => boolean;
method transform
transform: (value: T, metadata: ArgumentMetadata) => Promise<T>;
Method that accesses and performs optional transformation on argument for in-flight requests.
Parameter value
currently processed route argument
Parameter metadata
contains metadata about the currently processed route argument
class ParseFloatPipe
class ParseFloatPipe implements PipeTransform<string> {}
Defines the built-in ParseFloat Pipe
See Also
[Built-in Pipes](https://docs.nestjs.com/pipes#built-in-pipes)
constructor
constructor(options?: ParseFloatPipeOptions);
property exceptionFactory
protected exceptionFactory: (error: string) => any;
method isNumeric
protected isNumeric: (value: string) => boolean;
Parameter value
currently processed route argument
Returns
true
ifvalue
is a valid float number
method transform
transform: (value: string, metadata: ArgumentMetadata) => Promise<number>;
Method that accesses and performs optional transformation on argument for in-flight requests.
Parameter value
currently processed route argument
Parameter metadata
contains metadata about the currently processed route argument
class ParseIntPipe
class ParseIntPipe implements PipeTransform<string> {}
Defines the built-in ParseInt Pipe
See Also
[Built-in Pipes](https://docs.nestjs.com/pipes#built-in-pipes)
constructor
constructor(options?: ParseIntPipeOptions);
property exceptionFactory
protected exceptionFactory: (error: string) => any;
method isNumeric
protected isNumeric: (value: string) => boolean;
Parameter value
currently processed route argument
Returns
true
ifvalue
is a valid integer number
method transform
transform: (value: string, metadata: ArgumentMetadata) => Promise<number>;
Method that accesses and performs optional transformation on argument for in-flight requests.
Parameter value
currently processed route argument
Parameter metadata
contains metadata about the currently processed route argument
class ParseUUIDPipe
class ParseUUIDPipe implements PipeTransform<string> {}
constructor
constructor(options?: ParseUUIDPipeOptions);
property exceptionFactory
protected exceptionFactory: (errors: string) => any;
method transform
transform: (value: string, metadata: ArgumentMetadata) => Promise<string>;
class PayloadTooLargeException
class PayloadTooLargeException extends HttpException {}
Defines an HTTP exception for *Payload Too Large* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
PayloadTooLargeException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new PayloadTooLargeException()
The HTTP response status code will be 413. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 413. -message
: the string'Payload Too Large'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class PreconditionFailedException
class PreconditionFailedException extends HttpException {}
Defines an HTTP exception for *Precondition Failed* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
PreconditionFailedException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new PreconditionFailedException()
The HTTP response status code will be 412. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 412. -message
: the string'Precondition Failed'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class RequestTimeoutException
class RequestTimeoutException extends HttpException {}
Defines an HTTP exception for *Request Timeout* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
RequestTimeoutException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new RequestTimeoutException()
The HTTP response status code will be 408. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 408. -message
: the string'Request Timeout'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class ServiceUnavailableException
class ServiceUnavailableException extends HttpException {}
Defines an HTTP exception for *Service Unavailable* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate a
ServiceUnavailableException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new ServiceUnavailableException()
The HTTP response status code will be 503. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 503. -message
: the string'Service Unavailable'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class StreamableFile
class StreamableFile {}
constructor
constructor(buffer: Uint8Array, options?: StreamableFileOptions);
constructor
constructor(readable: Readable, options?: StreamableFileOptions);
property options
readonly options: StreamableFileOptions;
method getHeaders
getHeaders: () => { type: string; disposition: string; length: number };
method getStream
getStream: () => Readable;
class UnauthorizedException
class UnauthorizedException extends HttpException {}
Defines an HTTP exception for *Unauthorized* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate an
UnauthorizedException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new UnauthorizedException()
The HTTP response status code will be 401. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 401. -message
: the string'Unauthorized'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class UnprocessableEntityException
class UnprocessableEntityException extends HttpException {}
Defines an HTTP exception for *Unprocessable Entity* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate an
UnprocessableEntityException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new UnprocessableEntityException()
The HTTP response status code will be 422. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 422. -message
: the string'Unprocessable Entity'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class UnsupportedMediaTypeException
class UnsupportedMediaTypeException extends HttpException {}
Defines an HTTP exception for *Unsupported Media Type* type errors.
See Also
[Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
constructor
constructor(objectOrError?: any, description?: string);
Instantiate an
UnsupportedMediaTypeException
Exception.Parameter objectOrError
string or object describing the error condition.
Parameter description
a short description of the HTTP error.
Example 1
throw new UnsupportedMediaTypeException()
The HTTP response status code will be 415. - The
objectOrError
argument defines the JSON response body or the message string. - Thedescription
argument contains a short description of the HTTP error.By default, the JSON response body contains two properties: -
statusCode
: this will be the value 415. -message
: the string'Unsupported Media Type'
by default; override this by supplying a string in theobjectOrError
parameter.If the parameter
objectOrError
is a string, the response body will contain an additional property,error
, with a short description of the HTTP error. To override the entire JSON response body, pass an object instead. Nest will serialize the object and return it as the JSON response body.
class ValidationPipe
class ValidationPipe implements PipeTransform<any> {}
constructor
constructor(options?: ValidationPipeOptions);
property errorHttpStatusCode
protected errorHttpStatusCode: ErrorHttpStatusCode;
property exceptionFactory
protected exceptionFactory: (errors: ValidationError[]) => any;
property expectedType
protected expectedType: Type<any>;
property isDetailedOutputDisabled
protected isDetailedOutputDisabled?: boolean;
property isTransformEnabled
protected isTransformEnabled: boolean;
property transformOptions
protected transformOptions: ClassTransformOptions;
property validateCustomDecorators
protected validateCustomDecorators: boolean;
property validatorOptions
protected validatorOptions: ValidatorOptions;
method createExceptionFactory
createExceptionFactory: () => (validationErrors?: ValidationError[]) => unknown;
method flattenValidationErrors
protected flattenValidationErrors: ( validationErrors: ValidationError[]) => string[];
method isPrimitive
protected isPrimitive: (value: unknown) => boolean;
method loadTransformer
protected loadTransformer: ( transformerPackage?: TransformerPackage) => TransformerPackage;
method loadValidator
protected loadValidator: ( validatorPackage?: ValidatorPackage) => ValidatorPackage;
method mapChildrenToValidationErrors
protected mapChildrenToValidationErrors: ( error: ValidationError, parentPath?: string) => ValidationError[];
method prependConstraintsWithParentProp
protected prependConstraintsWithParentProp: ( parentPath: string, error: ValidationError) => ValidationError;
method stripProtoKeys
protected stripProtoKeys: (value: any) => void;
method toEmptyIfNil
protected toEmptyIfNil: <T = any, R = any>(value: T) => R | {};
method toValidate
protected toValidate: (metadata: ArgumentMetadata) => boolean;
method transform
transform: (value: any, metadata: ArgumentMetadata) => Promise<any>;
method transformPrimitive
protected transformPrimitive: (value: any, metadata: ArgumentMetadata) => any;
method validate
protected validate: ( object: object, validatorOptions?: ValidatorOptions) => Promise<ValidationError[]> | ValidationError[];
Interfaces
interface ArgumentMetadata
interface ArgumentMetadata {}
Interface describing a pipe implementation's
transform()
method metadata argument.See Also
[Pipes](https://docs.nestjs.com/pipes)
property data
readonly data?: string | undefined;
String passed as an argument to the decorator. Example:
@Body('userId')
would yielduserId
property metatype
readonly metatype?: Type<any> | undefined;
Underlying base type (e.g.,
String
) of the parameter, based on the type definition in the route handler.
property type
readonly type: Paramtype;
Indicates whether argument is a body, query, param, or custom parameter
interface ArgumentsHost
interface ArgumentsHost {}
Provides methods for retrieving the arguments being passed to a handler. Allows choosing the appropriate execution context (e.g., Http, RPC, or WebSockets) to retrieve the arguments from.
method getArgByIndex
getArgByIndex: <T = any>(index: number) => T;
Returns a particular argument by index.
Parameter index
index of argument to retrieve
method getArgs
getArgs: <T extends any[] = any[]>() => T;
Returns the array of arguments being passed to the handler.
method getType
getType: <TContext extends string = ContextType>() => TContext;
Returns the current execution context type (string)
method switchToHttp
switchToHttp: () => HttpArgumentsHost;
Switch context to HTTP.
Returns
interface with methods to retrieve HTTP arguments
method switchToRpc
switchToRpc: () => RpcArgumentsHost;
Switch context to RPC.
Returns
interface with methods to retrieve RPC arguments
method switchToWs
switchToWs: () => WsArgumentsHost;
Switch context to WebSockets.
Returns
interface with methods to retrieve WebSockets arguments
interface BeforeApplicationShutdown
interface BeforeApplicationShutdown {}
method beforeApplicationShutdown
beforeApplicationShutdown: (signal?: string) => any;
interface CacheManagerOptions
interface CacheManagerOptions {}
Interface defining Cache Manager configuration options.
property isCacheableValue
isCacheableValue?: (value: any) => boolean;
property max
max?: number;
Maximum number of responses to store in the cache. Defaults to 100.
property store
store?: string | CacheStoreFactory | CacheStore;
Cache storage manager. Default is
'memory'
(in-memory store). See [Different stores](https://docs.nestjs.com/techniques/caching#different-stores) for more info.
property ttl
ttl?: number;
Time to live - amount of time in seconds that a response is cached before it is deleted. Subsequent request will call through the route handler and refresh the cache. Defaults to 5 seconds.
interface CacheModuleAsyncOptions
interface CacheModuleAsyncOptions< StoreConfig extends Record<any, any> = Record<string, any>> extends Pick<ModuleMetadata, 'imports'> {}
Options for dynamically configuring the Cache module.
See Also
[Async configuration](https://docs.nestjs.com/techniques/caching#async-configuration)
property extraProviders
extraProviders?: Provider[];
property inject
inject?: any[];
Dependencies that a Factory may inject.
property isGlobal
isGlobal?: boolean;
If "true', register
CacheModule
as a global module.
property useClass
useClass?: Type<CacheOptionsFactory<StoreConfig>>;
Injection token resolving to a class that will be instantiated as a provider. The class must implement the
CacheOptionsFactory
interface.
property useExisting
useExisting?: Type<CacheOptionsFactory<StoreConfig>>;
Injection token resolving to an existing provider. The provider must implement the
CacheOptionsFactory
interface.
property useFactory
useFactory?: ( ...args: any[]) => Promise<CacheModuleOptions<StoreConfig>> | CacheModuleOptions<StoreConfig>;
Function returning options (or a Promise resolving to options) to configure the cache module.
interface CacheOptionsFactory
interface CacheOptionsFactory< StoreConfig extends Record<any, any> = Record<string, any>> {}
Interface describing a
CacheOptionsFactory
. Providers supplying configuration options for the Cache module must implement this interface.See Also
[Async configuration](https://docs.nestjs.com/techniques/caching#async-configuration)
method createCacheOptions
createCacheOptions: () => | Promise<CacheModuleOptions<StoreConfig>> | CacheModuleOptions<StoreConfig>;
interface CacheStore
interface CacheStore {}
Interface defining a cache store. Implement this interface to create a custom cache store.
method del
del: (key: string) => void | Promise<void>;
Destroy a key/value pair from the cache.
Parameter key
cache key
method get
get: <T>(key: string) => Promise<T | undefined> | T | undefined;
Retrieve a key/value pair from the cache.
Parameter key
cache key
method set
set: <T>( key: string, value: T, options?: CacheStoreSetOptions<T>) => Promise<void> | void;
Create a key/value pair in the cache.
Parameter key
cache key
Parameter value
cache value
interface CacheStoreFactory
interface CacheStoreFactory {}
Interface defining a factory to create a cache store.
method create
create: (args: LiteralObject) => CacheStore;
Return a configured cache store.
Parameter args
Cache manager options received from
CacheModule.register()
orCacheModule.registerAsync()
interface CacheStoreSetOptions
interface CacheStoreSetOptions<T> {}
property ttl
ttl?: ((value: T) => number) | number;
Time to live - amount of time in seconds that a response is cached before it is deleted. Defaults based on your cache manager settings.
interface CallHandler
interface CallHandler<T = any> {}
Interface providing access to the response stream.
See Also
[Interceptors](https://docs.nestjs.com/interceptors)
method handle
handle: () => Observable<T>;
Returns an
Observable
representing the response stream from the route handler.
interface CanActivate
interface CanActivate {}
Interface defining the
canActivate()
function that must be implemented by a guard. Return value indicates whether or not the current request is allowed to proceed. Return can be either synchronous (boolean
) or asynchronous (Promise
orObservable
).See Also
[Guards](https://docs.nestjs.com/guards)
method canActivate
canActivate: ( context: ExecutionContext) => boolean | Promise<boolean> | Observable<boolean>;
Parameter context
Current execution context. Provides access to details about the current request pipeline.
Returns
Value indicating whether or not the current request is allowed to proceed.
interface ClassProvider
interface ClassProvider<T = any> {}
Interface defining a *Class* type provider.
For example:
const configServiceProvider = {provide: ConfigService,useClass:process.env.NODE_ENV === 'development'? DevelopmentConfigService: ProductionConfigService,};See Also
[Class providers](https://docs.nestjs.com/fundamentals/custom-providers#class-providers-useclass)
[Injection scopes](https://docs.nestjs.com/fundamentals/injection-scopes)
interface ClassSerializerInterceptorOptions
interface ClassSerializerInterceptorOptions extends ClassTransformOptions {}
property transformerPackage
transformerPackage?: TransformerPackage;
interface ConsoleLoggerOptions
interface ConsoleLoggerOptions {}
interface ControllerOptions
interface ControllerOptions extends ScopeOptions, VersionOptions {}
Interface defining options that can be passed to
@Controller()
decorator
property host
host?: string | RegExp | Array<string | RegExp>;
Specifies an optional HTTP Request host filter. When configured, methods within the controller will only be routed if the request host matches the specified value.
See Also
[Routing](https://docs.nestjs.com/controllers#routing)
property path
path?: string | string[];
Specifies an optional
route path prefix
. The prefix is pre-pended to the path specified in any request decorator in the class.Supported only by HTTP-based applications (does not apply to non-HTTP microservices).
See Also
[Routing](https://docs.nestjs.com/controllers#routing)
interface DynamicModule
interface DynamicModule extends ModuleMetadata {}
Interface defining a Dynamic Module.
See Also
[Dynamic Modules](https://docs.nestjs.com/modules#dynamic-modules)
property global
global?: boolean;
When "true", makes a module global-scoped.
Once imported into any module, a global-scoped module will be visible in all modules. Thereafter, modules that wish to inject a service exported from a global module do not need to import the provider module.
false
property module
module: Type<any>;
A module reference
interface ExceptionFilter
interface ExceptionFilter<T = any> {}
Interface describing implementation of an exception filter.
See Also
[Exception Filters](https://docs.nestjs.com/exception-filters)
method catch
catch: (exception: T, host: ArgumentsHost) => any;
Method to implement a custom exception filter.
Parameter exception
the class of the exception being handled
Parameter host
used to access an array of arguments for the in-flight request
interface ExecutionContext
interface ExecutionContext extends ArgumentsHost {}
Interface describing details about the current request pipeline.
See Also
[Execution Context](https://docs.nestjs.com/guards#execution-context)
method getClass
getClass: <T = any>() => Type<T>;
Returns the *type* of the controller class which the current handler belongs to.
method getHandler
getHandler: () => Function;
Returns a reference to the handler (method) that will be invoked next in the request pipeline.
interface ExistingProvider
interface ExistingProvider<T = any> {}
Interface defining an *Existing* (aliased) type provider.
For example:
const loggerAliasProvider = {provide: 'AliasedLoggerService',useExisting: LoggerService};See Also
[Alias providers](https://docs.nestjs.com/fundamentals/custom-providers#alias-providers-useexisting)
property provide
provide: InjectionToken;
Injection token
property useExisting
useExisting: any;
Provider to be aliased by the Injection token.
interface FactoryProvider
interface FactoryProvider<T = any> {}
Interface defining a *Factory* type provider.
For example:
const connectionFactory = {provide: 'CONNECTION',useFactory: (optionsProvider: OptionsProvider) => {const options = optionsProvider.get();return new DatabaseConnection(options);},inject: [OptionsProvider],};See Also
[Factory providers](https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory)
[Injection scopes](https://docs.nestjs.com/fundamentals/injection-scopes)
property inject
inject?: Array<InjectionToken | OptionalFactoryDependency>;
Optional list of providers to be injected into the context of the Factory function.
property provide
provide: InjectionToken;
Injection token
property scope
scope?: Scope;
Optional enum defining lifetime of the provider that is returned by the Factory function.
property useFactory
useFactory: (...args: any[]) => T;
Factory function that returns an instance of the provider to be injected.
interface ForwardReference
interface ForwardReference<T = any> {}
property forwardRef
forwardRef: T;
interface HttpAdapterHost
interface HttpAdapterHost<T extends HttpServer = any> {}
property httpAdapter
httpAdapter: T;
interface HttpModuleAsyncOptions
interface HttpModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {}
property extraProviders
extraProviders?: Provider[];
property inject
inject?: any[];
property useClass
useClass?: Type<HttpModuleOptionsFactory>;
property useExisting
useExisting?: Type<HttpModuleOptionsFactory>;
property useFactory
useFactory?: (...args: any[]) => Promise<HttpModuleOptions> | HttpModuleOptions;
interface HttpModuleOptionsFactory
interface HttpModuleOptionsFactory {}
method createHttpOptions
createHttpOptions: () => Promise<HttpModuleOptions> | HttpModuleOptions;
interface HttpServer
interface HttpServer<TRequest = any, TResponse = any> {}
method all
all: { (path: string, handler: RequestHandler<TRequest, TResponse>): any; (handler: RequestHandler<TRequest, TResponse>): any;};
method applyVersionFilter
applyVersionFilter: ( handler: Function, version: VersionValue, versioningOptions: VersioningOptions) => <TRequest extends Record<string, any> = any, TResponse = any>( req: TRequest, res: TResponse, next: () => void) => any;
method close
close: () => any;
method createMiddlewareFactory
createMiddlewareFactory: ( method: RequestMethod) => | ((path: string, callback: Function) => any) | Promise<(path: string, callback: Function) => any>;
method delete
delete: { (handler: RequestHandler<TRequest, TResponse>): any; (path: string, handler: RequestHandler<TRequest, TResponse>): any;};
method enableCors
enableCors: (options: CorsOptions | CorsOptionsDelegate<TRequest>) => any;
method get
get: { (handler: RequestHandler<TRequest, TResponse>): any; (path: string, handler: RequestHandler<TRequest, TResponse>): any;};
method getHttpServer
getHttpServer: () => any;
method getInstance
getInstance: () => any;
method getRequestHostname
getRequestHostname: (request: TRequest) => string;
method getRequestMethod
getRequestMethod: (request: TRequest) => string;
method getRequestUrl
getRequestUrl: (request: TRequest) => string;
method getType
getType: () => string;
method head
head: { (handler: RequestHandler<TRequest, TResponse>): any; (path: string, handler: RequestHandler<TRequest, TResponse>): any;};
method init
init: () => Promise<void>;
method initHttpServer
initHttpServer: (options: NestApplicationOptions) => void;
method listen
listen: { (port: number | string, callback?: () => void): any; (port: string | number, hostname: string, callback?: () => void): any;};
method options
options: { (handler: RequestHandler<TRequest, TResponse>): any; (path: string, handler: RequestHandler<TRequest, TResponse>): any;};
method patch
patch: { (handler: RequestHandler<TRequest, TResponse>): any; (path: string, handler: RequestHandler<TRequest, TResponse>): any;};
method post
post: { (handler: RequestHandler<TRequest, TResponse>): any; (path: string, handler: RequestHandler<TRequest, TResponse>): any;};
method put
put: { (handler: RequestHandler<TRequest, TResponse>): any; (path: string, handler: RequestHandler<TRequest, TResponse>): any;};
method redirect
redirect: (response: any, statusCode: number, url: string) => any;
method registerParserMiddleware
registerParserMiddleware: (...args: any[]) => any;
method render
render: (response: any, view: string, options: any) => any;
method reply
reply: (response: any, body: any, statusCode?: number) => any;
method setBaseViewsDir
setBaseViewsDir: (path: string | string[]) => this;
method setErrorHandler
setErrorHandler: (handler: Function, prefix?: string) => any;
method setHeader
setHeader: (response: any, name: string, value: string) => any;
method setNotFoundHandler
setNotFoundHandler: (handler: Function, prefix?: string) => any;
method setViewEngine
setViewEngine: (engineOrOptions: any) => this;
method status
status: (response: any, statusCode: number) => any;
method use
use: { ( handler: | RequestHandler<TRequest, TResponse> | ErrorHandler<TRequest, TResponse> ): any; ( path: string, handler: | RequestHandler<TRequest, TResponse> | ErrorHandler<TRequest, TResponse> ): any;};
method useStaticAssets
useStaticAssets: (...args: any[]) => this;
interface INestApplication
interface INestApplication extends INestApplicationContext {}
Interface defining the core NestApplication object.
method close
close: () => Promise<void>;
Terminates the application (including NestApplication, Gateways, and each connected microservice)
Returns
{Promise}
method connectMicroservice
connectMicroservice: <T extends object = any>( options: T, hybridOptions?: NestHybridApplicationOptions) => INestMicroservice;
Connects microservice to the NestApplication instance. Transforms application to a hybrid instance.
{object} T
Parameter options
Microservice options object
Parameter hybridOptions
Hybrid options object
Returns
{INestMicroservice}
method enableCors
enableCors: (options?: CorsOptions | CorsOptionsDelegate<any>) => void;
Enables CORS (Cross-Origin Resource Sharing)
Returns
{void}
method enableVersioning
enableVersioning: (options?: VersioningOptions) => this;
Enables Versioning for the application. By default, URI-based versioning is used.
Parameter options
Returns
{this}
method getHttpAdapter
getHttpAdapter: () => HttpServer;
Returns the underlying HTTP adapter.
Returns
{HttpServer}
method getHttpServer
getHttpServer: () => any;
Returns the underlying native HTTP server.
Returns
{*}
method getMicroservices
getMicroservices: () => INestMicroservice[];
Returns array of the microservices connected to the NestApplication.
Returns
{INestMicroservice[]}
method getUrl
getUrl: () => Promise<string>;
Returns the url the application is listening at, based on OS and IP version. Returns as an IP value either in IPv6 or IPv4
Returns
{Promise} The IP where the server is listening
method listen
listen: { (port: number | string, callback?: () => void): Promise<any>; ( port: string | number, hostname: string, callback?: () => void ): Promise<any>;};
Starts the application.
Parameter port
Parameter hostname
Parameter callback
Optional callback
Returns
{Promise} A Promise that, when resolved, is a reference to the underlying HttpServer.
method listenAsync
listenAsync: (port: number | string, hostname?: string) => Promise<any>;
Starts the application (can be awaited).
Parameter port
Parameter hostname
Returns
{Promise}
Deprecated
use "listen" instead.
method setGlobalPrefix
setGlobalPrefix: (prefix: string, options?: GlobalPrefixOptions) => this;
Registers a prefix for every HTTP route path.
Parameter prefix
The prefix for every HTTP route path (for example
/v1/api
)Parameter options
Global prefix options object
Returns
{this}
method startAllMicroservices
startAllMicroservices: () => Promise<this>;
Starts all connected microservices asynchronously.
Returns
{Promise}
method startAllMicroservicesAsync
startAllMicroservicesAsync: () => Promise<this>;
Starts all connected microservices and can be awaited.
Returns
{Promise}
Deprecated
use "startAllMicroservices" instead.
method use
use: (...args: any[]) => this;
A wrapper function around HTTP adapter method:
adapter.use()
. Exampleapp.use(cors())
Returns
{this}
method useGlobalFilters
useGlobalFilters: (...filters: ExceptionFilter[]) => this;
Registers exception filters as global filters (will be used within every HTTP route handler)
Parameter filters
method useGlobalGuards
useGlobalGuards: (...guards: CanActivate[]) => this;
Registers guards as global guards (will be used within every HTTP route handler)
Parameter guards
method useGlobalInterceptors
useGlobalInterceptors: (...interceptors: NestInterceptor[]) => this;
Registers interceptors as global interceptors (will be used within every HTTP route handler)
Parameter interceptors
method useGlobalPipes
useGlobalPipes: (...pipes: PipeTransform<any>[]) => this;
Registers pipes as global pipes (will be used within every HTTP route handler)
Parameter pipes
method useWebSocketAdapter
useWebSocketAdapter: (adapter: WebSocketAdapter) => this;
Register Ws Adapter which will be used inside Gateways. Use when you want to override default
socket.io
library.Parameter adapter
Returns
{this}
interface INestApplicationContext
interface INestApplicationContext {}
Interface defining NestApplicationContext.
method close
close: () => Promise<void>;
Terminates the application
Returns
{Promise}
method enableShutdownHooks
enableShutdownHooks: (signals?: ShutdownSignal[] | string[]) => this;
Enables the usage of shutdown hooks. Will call the
onApplicationShutdown
function of a provider if the process receives a shutdown signal.Returns
{this} The Nest application context instance
method flushLogs
flushLogs: () => void;
Prints buffered logs and detaches buffer.
Returns
{void}
method get
get: <TInput = any, TResult = TInput>( typeOrToken: Type<TInput> | Function | string | symbol, options?: { strict: boolean }) => TResult;
Retrieves an instance of either injectable or controller, otherwise, throws exception.
Returns
{TResult}
method init
init: () => Promise<this>;
Initalizes the Nest application. Calls the Nest lifecycle events. It isn't mandatory to call this method directly.
Returns
{Promise} The NestApplicationContext instance as Promise
method registerRequestByContextId
registerRequestByContextId: <T = any>( request: T, contextId: { id: number }) => 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, contextId?: { id: number }, options?: { strict: boolean }) => Promise<TResult>;
Resolves transient or request-scoped instance of either injectable or controller, otherwise, throws exception.
Returns
{Promise}
method select
select: <T>(module: Type<T> | DynamicModule) => INestApplicationContext;
Allows navigating through the modules tree, for example, to pull out a specific instance from the selected module.
Returns
{INestApplicationContext}
method useLogger
useLogger: (logger: LoggerService | LogLevel[] | false) => void;
Sets custom logger service. Flushes buffered logs if auto flush is on.
Returns
{void}
interface INestMicroservice
interface INestMicroservice extends INestApplicationContext {}
Interface describing Microservice Context.
method close
close: () => Promise<void>;
Terminates the application
Returns
{Promise}
method listen
listen: () => Promise<any>;
Starts the microservice.
Returns
{void}
method listenAsync
listenAsync: () => Promise<any>;
Starts the microservice (can be awaited).
Returns
{Promise}
Deprecated
use "listen" instead.
method useGlobalFilters
useGlobalFilters: (...filters: ExceptionFilter[]) => this;
Registers exception filters as global filters (will be used within every message pattern handler)
Parameter filters
method useGlobalGuards
useGlobalGuards: (...guards: CanActivate[]) => this;
Registers guards as global guards (will be used within every message pattern handler)
Parameter guards
method useGlobalInterceptors
useGlobalInterceptors: (...interceptors: NestInterceptor[]) => this;
Registers interceptors as global interceptors (will be used within every message pattern handler)
Parameter interceptors
method useGlobalPipes
useGlobalPipes: (...pipes: PipeTransform<any>[]) => this;
Registers pipes as global pipes (will be used within every message pattern handler)
Parameter pipes
method useWebSocketAdapter
useWebSocketAdapter: (adapter: WebSocketAdapter) => this;
Register Ws Adapter which will be used inside Gateways. Use when you want to override default
socket.io
library.Parameter adapter
Returns
{this}
interface IntrospectionResult
interface IntrospectionResult {}
property scope
scope: Scope;
Enum defining lifetime of host class or factory.
interface LiteralObject
interface LiteralObject {}
index signature
[key: string]: any;
interface LoggerService
interface LoggerService {}
method debug
debug: (message: any, ...optionalParams: any[]) => any;
Write a 'debug' level log.
method error
error: (message: any, ...optionalParams: any[]) => any;
Write an 'error' level log.
method log
log: (message: any, ...optionalParams: any[]) => any;
Write a 'log' level log.
method setLogLevels
setLogLevels: (levels: LogLevel[]) => any;
Set log levels.
Parameter levels
log levels
method verbose
verbose: (message: any, ...optionalParams: any[]) => any;
Write a 'verbose' level log.
method warn
warn: (message: any, ...optionalParams: any[]) => any;
Write a 'warn' level log.
interface MessageEvent
interface MessageEvent {}
interface MiddlewareConsumer
interface MiddlewareConsumer {}
Interface defining method for applying user defined middleware to routes.
See Also
[MiddlewareConsumer](https://docs.nestjs.com/middleware#middleware-consumer)
method apply
apply: (...middleware: (Type<any> | Function)[]) => MiddlewareConfigProxy;
Parameter middleware
middleware class/function or array of classes/functions to be attached to the passed routes.
Returns
{MiddlewareConfigProxy}
interface ModuleMetadata
interface ModuleMetadata {}
Interface defining the property object that describes the module.
See Also
[Modules](https://docs.nestjs.com/modules)