Compare commits

...

9 Commits

Author SHA1 Message Date
Kamil Myśliwiec
3c1a6a2f97 refactor() add whitespace to gulp config 2019-08-24 19:24:18 +02:00
Kamil Myśliwiec
09ce572d8f refactor(docs) small docs, comments fixes 2019-08-24 19:23:54 +02:00
Kamil Myśliwiec
3671a1b359 Merge branch 'feature/api-docs' of https://github.com/BrunnerLivio/nest into BrunnerLivio-feature/api-docs 2019-08-24 10:50:50 +02:00
Livio
738e00ebb0 lint(core): Remove trailing whitespace 2019-08-15 17:36:03 +02:00
John Biundo
9edd0444e5 feat(common): Add documentation for public API 2019-08-15 17:26:11 +02:00
John Biundo
b840b1974c feat(platform-express): Add documentation for public API 2019-08-15 17:25:27 +02:00
John Biundo
63262c38f6 feat(core): Add documentation for public API 2019-08-15 17:25:27 +02:00
Livio
e76786b1b1 feat(): Add package description files 2019-08-15 17:25:27 +02:00
Livio
68721a2539 feat(): Add ScopeOptions to public API
Mandatory so the public API parser
of docs.nestjs.com can compute this interface
2019-08-15 17:25:27 +02:00
39 changed files with 813 additions and 62 deletions

View File

@@ -0,0 +1 @@
The common package comes with decorators such as `@Controller()`, `@Injectable()` and so on.

View File

@@ -1,7 +1,7 @@
/**
* Binds parameter decorators to the method
* Useful when the language doesn't provide a 'Parameter Decorators' feature (vanilla JavaScript)
* @param {} ...decorators
* @param ...decorators
*/
export function Bind(...decorators: any[]): MethodDecorator {
return <T>(

View File

@@ -2,17 +2,83 @@ import { PATH_METADATA, SCOPE_OPTIONS_METADATA } from '../../constants';
import { isString, isUndefined } from '../../utils/shared.utils';
import { ScopeOptions } from './../../interfaces/scope-options.interface';
/**
*
* Interface defining options that can be passed to `@Controller()` decorator
* @publicApi
*/
export interface ControllerOptions extends ScopeOptions {
/**
* Specifies an optional route path prefix. When specified, the route path
* for a handler is determined by concatenating the prefix with any path
*
* @see [Routing](https://docs.nestjs.com/controllers#routing)
*/
path?: string;
}
export function Controller();
export function Controller(prefix: string);
export function Controller(options: ControllerOptions);
/**
* Defines the controller. Controller can inject dependencies through constructor.
* Those dependencies have to belong to the same module.
* Decorator that marks a class as a Nest controller that can receive inbound
* requests and produce responses.
*
* HTTP Controllers optionally accept configuration
* metadata that determines route paths that route handlers in the class
* respond to, and lifetime [scope](https://docs.nestjs.com/fundamentals/injection-scopes#usage).
*
* 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
* (e.g., `GET /api/profile`, `POST /user/resume`).
*
* A Microservice Controller responds to Requests and Responses, 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 [Controllers](https://docs.nestjs.com/controllers)
* @see [Microservices](https://docs.nestjs.com/microservices/basics#request-response)
*
* @usageNotes
*
* ### Setting controller options
* The controller decorator takes an optional options object in plain JSON format.
* This object can take properties `path` and `scope`.
*
* ### Setting the default route path prefix
* The following example sets `cats` as the default route path prefix for all route
* handlers in this controller. When simply passing a route prefix, you can pass
* it as a string as shown in the example below.
*
* ```typescript
* @Controller('cats')
* export class CatsController {
* @Get()
* findall(): string {
* return 'This action returns all cats';
* }
* }
* ```
* This route handler will respond to the request
* `GET /cats`
*
* ### Setting the injection scope
* The following example sets the scope for all requests in the controller
* to request-scoped. Each request will cause Nest to create a new instance of
* the controller.
* ```typescript
* @Controller({
* path: 'cats',
* scope: Scope.REQUEST,
* })
* export class CatsController { ... }
* ```
*
* [Read more about scopes here.](https://docs.nestjs.com/fundamentals/injection-scopes)
*
* @publicApi
*/
export function Controller(): ClassDecorator;
export function Controller(prefix: string): ClassDecorator;
export function Controller(options: ControllerOptions): ClassDecorator;
export function Controller(
prefixOrOptions?: string | ControllerOptions,
): ClassDecorator {
@@ -20,8 +86,8 @@ export function Controller(
const [path, scopeOptions] = isUndefined(prefixOrOptions)
? [defaultPath, undefined]
: isString(prefixOrOptions)
? [prefixOrOptions, undefined]
: [prefixOrOptions.path || defaultPath, { scope: prefixOrOptions.scope }];
? [prefixOrOptions, undefined]
: [prefixOrOptions.path || defaultPath, { scope: prefixOrOptions.scope }];
return (target: object) => {
Reflect.defineMetadata(PATH_METADATA, path, target);

View File

@@ -5,9 +5,81 @@ import {
import { isFunction, isUndefined } from '../../utils/shared.utils';
/**
* Injects provider which has to be available in the current injector (module) scope.
* Providers are recognized by either types or tokens.
* Decorator that marks a constructor parameter as a target for
* [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection). Takes a single
* required parameter which is the
* [injection token](https://docs.nestjs.com/fundamentals/custom-providers). The injection token serves
* as the lookup key for the [provider](https://docs.nestjs.com/providers) that will be injected
* (assigned to the constructor parameter).
*
* 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.
*
* 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
*
* @see [Providers](https://docs.nestjs.com/providers)
* @see [Custom Providers](https://docs.nestjs.com/fundamentals/custom-providers)
* @see [Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes)
*
* @usageNotes
*
* #### Injecting with a type (class name)
*
* ```typescript
* import { Inject } from '@nestjs/common';
* import { ConfigService } from './config.service';
*
* export class CatsService {
* constructor(@Inject(ConfigService) private readonly configService) {}
* }
* ```
*
* The above is equivalent to the conventional constructor injection syntax:
* ```typescript
* import { ConfigService } from './config.service';
*
* export class CatsService {
* constructor(private readonly configService: ConfigService) {}
* }
* ```
* #### Injecting with a string
*
* Assume we've registered a provider with the string `'CONNECTION'` as follows:
*
* ```typescript
* import { connection } from './connection';
* const connectionProvider = {
* provide: 'CONNECTION',
* useValue: connection,
* };
*
* @Module({
* providers: [connectionProvider],
* })
* export class ApplicationModule {}
* ```
* As a result, we now have a provider bound to the DI container using the
* injection token `'CONNECTION'`. This provider can be injected as follows:
*
* ```typescript
* @Injectable()
* export class CatsRepository {
* constructor(@Inject('CONNECTION') connection: Connection) {}
* }
* ```
* @publicApi
*/
export function Inject<T = any>(token?: T) {
return (target: Object, key: string | symbol, index?: number) => {
token = token || Reflect.getMetadata('design:type', target, key);

View File

@@ -3,11 +3,110 @@ import { ScopeOptions } from '../../interfaces/scope-options.interface';
import { SCOPE_OPTIONS_METADATA } from './../../constants';
import { Type } from './../../interfaces/type.interface';
/**
* Defines the injection scope.
*
* @see [Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes)
*
* @publicApi
*/
export interface InjectableOptions extends ScopeOptions {}
/**
* Defines the injectable class. This class can inject dependencies through constructor.
* Those dependencies have to belong to the same module.
* 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()` decorator
*
* Providers 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.
*
* @see [Providers](https://docs.nestjs.com/providers)
* @see [Custom Providers](https://docs.nestjs.com/fundamentals/custom-providers)
* @see [Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes)
*
* @usageNotes
*
* #### Setting provider scope
*
* The `@Injector()` decorator takes an optional options object in plain JSON format.
* This object has one property: `scope`.
*
* Following is an example of setting a provider's scope to per-request. See more
* about [injection scopes here](https://docs.nestjs.com/fundamentals/injection-scopes).
*
* ```typescript
* import { Injectable, Scope } from '@nestjs/common';
*
* @Injectable({ scope: Scope.REQUEST })
* export class CatsService {}
* ```
*
* #### Declaring providers
*
* Providers are declared using the `@Injectable()` decorator and a standard
* JavaScript class.
*
* ```typescript
* import { Injectable } from '@nestjs/common';
* import { Cat } from './interfaces/cat.interface';
*
* @Injectable()
* export class CatsService {
* private readonly cats: Cat[] = [];
*
* create(cat: Cat) {
* this.cats.push(cat);
* }
*
* findAll(): Cat[] {
* return this.cats;
* }
* }
* ```
*
* #### Using providers
*
* Providers created using the `@Injectable()` decorator use an
* [injection token](https://docs.nestjs.com/fundamentals/custom-providers) that is the class type.
*
* For example to inject the provider declared above using constructor injection,
* use the following syntax. In this example, `CatsService` is the name of
* the provider class declared earlier, and is used as the injection token in
* the constructor.
*
* ```typescript
* import { Controller, Get, Post, Body } from '@nestjs/common';
* import { CreateCatDto } from './dto/create-cat.dto';
* import { CatsService } from './cats.service';
* import { Cat } from './interfaces/cat.interface';
*
* @Controller('cats')
* export class CatsController {
* constructor(private readonly catsService: CatsService) {}
*
* @Post()
* async create(@Body() createCatDto: CreateCatDto) {
* this.catsService.create(createCatDto);
* }
*
* @Get()
* async findAll(): Promise<Cat[]> {
* return this.catsService.findAll();
* }
* }
* ```
* @publicApi
*/
export function Injectable(options?: InjectableOptions): ClassDecorator {
return (target: object) => {

View File

@@ -5,14 +5,38 @@ import { isFunction } from '../../utils/shared.utils';
import { validateEach } from '../../utils/validate-each.util';
/**
* Binds guards to the particular context.
* When the `@UseGuards()` is used on the controller level:
* - Guard will be register to each handler (every method)
* Decorator that binds guards to the scope of the controller or method,
* depending on its context.
*
* When the `@UseGuards()` is used on the handler level:
* - Guard will be registered only to the specified method
* When `@UseGuards` is used at the controller level, the guard will be
* applied to every handler (method) in the controller.
*
* @param {} ...guards
* When `@UseGuards` is used at the individual handler level, the guard
* will apply only to that specific method.
*
* @see [Guards](https://docs.nestjs.com/guards)
*
* @usageNotes
*
* ### Passing a guard by type
* In this example, we pass a guard type, which will delegate instantiating
* the guard to the Nest framework, and will allow Dependency Injection.
*
* ```typescript
* @Controller('cats')
* @UseGuards(RolesGuard)
* export class CatsController {}
* ```
*
* ### Passing a guard instance
* It's also possible to pass an instance of a guard directly to the decorator.
*
* ```typescript
* @Controller('cats')
* @UseGuards(new RolesGuard())
* export class CatsController {}
* ```
* @publicApi
*/
export function UseGuards(...guards: (CanActivate | Function)[]) {
return (target: any, key?: string, descriptor?: any) => {

View File

@@ -12,7 +12,7 @@ import { validateEach } from '../../utils/validate-each.util';
* When the `@UseInterceptors()` is used on the handle level:
* - Interceptor will be registered only to the specified method
*
* @param {} ...interceptors
* @param ...interceptors
*/
export function UseInterceptors(
...interceptors: (NestInterceptor | Function)[]

View File

@@ -3,6 +3,12 @@ import { extendArrayMetadata } from '../../utils/extend-metadata.util';
/**
* Sets a response header.
*
* Example: `@Header('Cache-Control', 'none')`
*
* @see [Headers](https://docs.nestjs.com/controllers#headers)
*
* @publicApi
*/
export function Header(name: string, value: string): MethodDecorator {
return (target: object, key, descriptor) => {

View File

@@ -1,10 +1,13 @@
import { HTTP_CODE_METADATA } from '../../constants';
/**
* Defines the HTTP response status code.
* It overrides default status code for the given request method.
* @publicApi
*
* @param {number} statusCode
* @description
* Defines the HTTP response status code. Overrides default status code for
* the decorated request method.
*
* @see [Http Status Codes](https://docs.nestjs.com/controllers#status-code)
*/
export function HttpCode(statusCode: number): MethodDecorator {
return (target: object, key, descriptor) => {

View File

@@ -1,7 +1,9 @@
import { REDIRECT_METADATA } from '../../constants';
/**
* Redirects request.
* Redirects request to the specified URL.
*
* @publicApi
*/
export function Redirect(url: string): MethodDecorator {
return (target: object, key, descriptor) => {

View File

@@ -2,6 +2,11 @@ import { RENDER_METADATA } from '../../constants';
/**
* Defines a template to be rendered by the controller.
*
* Example: `@Render('index)`
*
* @see [Example](https://github.com/nestjs/nest/blob/master/sample/15-mvc/src/app.controller.ts)
* @publicApi
*/
export function Render(template: string): MethodDecorator {
return (target: object, key, descriptor) => {

View File

@@ -31,41 +31,81 @@ const createMappingDecorator = (method: RequestMethod) => (
};
/**
* @publicApi
*
* @description
* Routes HTTP POST requests to the specified path.
*
* @see [Routing](https://docs.nestjs.com/controllers#routing)
*/
export const Post = createMappingDecorator(RequestMethod.POST);
/**
* @publicApi
*
* @description
* Routes HTTP GET requests to the specified path.
*
* @see [Routing](https://docs.nestjs.com/controllers#routing)
*/
export const Get = createMappingDecorator(RequestMethod.GET);
/**
* @publicApi
*
* @description
* Routes HTTP DELETE requests to the specified path.
*
* @see [Routing](https://docs.nestjs.com/controllers#routing)
*/
export const Delete = createMappingDecorator(RequestMethod.DELETE);
/**
* @publicApi
*
* @description
* Routes HTTP PUT requests to the specified path.
*
* @see [Routing](https://docs.nestjs.com/controllers#routing)
*/
export const Put = createMappingDecorator(RequestMethod.PUT);
/**
* @publicApi
*
* @description
* Routes HTTP PATCH requests to the specified path.
*
* @see [Routing](https://docs.nestjs.com/controllers#routing)
*/
export const Patch = createMappingDecorator(RequestMethod.PATCH);
/**
* @publicApi
*
* @description
* Routes HTTP OPTIONS requests to the specified path.
*
* @see [Routing](https://docs.nestjs.com/controllers#routing)
*/
export const Options = createMappingDecorator(RequestMethod.OPTIONS);
/**
* @publicApi
*
* @description
* Routes HTTP HEAD requests to the specified path.
*
* @see [Routing](https://docs.nestjs.com/controllers#routing)
*/
export const Head = createMappingDecorator(RequestMethod.HEAD);
/**
* @publicApi
*
* @description
* Routes all HTTP requests to the specified path.
*
* @see [Routing](https://docs.nestjs.com/controllers#routing)
*/
export const All = createMappingDecorator(RequestMethod.ALL);

View File

@@ -76,6 +76,19 @@ export const UploadedFile: (
export const UploadedFiles: () => ParameterDecorator = createRouteParamDecorator(
RouteParamtypes.FILES,
);
/**
* Route handler parameter decorator. Extracts the `headers`
* property from the `req` object and populates the decorated
* parameter with the value of `headers`.
*
* `property` - optional name of single header property to extract.
*
* Example: `async update(@Headers() headers)`
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export const Headers: (
property?: string,
) => ParameterDecorator = createRouteParamDecorator(RouteParamtypes.HEADERS);
@@ -88,6 +101,17 @@ export function Query(
property: string,
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `query`
* property from the `req` object and populates the decorated
* parameter with the value of `query`.
*
* Example: `async find(@Query() query: string)`
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export function Query(
property?: string | (Type<PipeTransform> | PipeTransform),
...pipes: (Type<PipeTransform> | PipeTransform)[]
@@ -106,6 +130,17 @@ export function Body(
property: string,
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `body`
* property from the `req` object and populates the decorated
* parameter with the value of `body`.
*
* Example: `async create(@Body() createCatDto: CreateCatDto)`
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export function Body(
property?: string | (Type<PipeTransform> | PipeTransform),
...pipes: (Type<PipeTransform> | PipeTransform)[]

View File

@@ -1,8 +1,38 @@
import { GLOBAL_MODULE_METADATA } from '../../constants';
/**
* @publicApi
*
* @description
*
* Makes the module global-scoped.
* Once imported will be available for all existing modules.
* Once imported into any module, the global-scoped module will be visible
* in all modules.
*
* @see [Global modules](https://docs.nestjs.com/modules#global-modules)
*
* @usageNotes
*
* `@Global()` makes the `CatsModule` global-scoped. The CatsService provider
* will be ubiquitous, and modules that wish to inject the service will not need to import the CatsModule in their imports array.
*
* Note that the `imports` array is generally the preferred way to make a module's
* API available to consumers.
*
* ```typescript
* import { Module, Global } from '@nestjs/common';
* import { CatsController } from './cats.controller';
* import { CatsService } from './cats.service';
*
* @Global()
* @Module({
* controllers: [CatsController],
* providers: [CatsService],
* exports: [CatsService],
* })
*
* export class CatsModule {}
* ```
*/
export function Global(): ClassDecorator {
return (target: any) => {

View File

@@ -21,12 +21,37 @@ const validateKeys = (keys: string[]) => {
};
/**
* Defines the module
* - `imports` - the set of the 'imported' modules
* - `controllers` - the list of controllers (e.g. HTTP controllers)
* - `providers` - the list of providers that belong to this module. They can be injected between themselves.
* - `exports` - the set of components, which should be available for modules, which imports this module
* @param metadata {ModuleMetadata} Module metadata
* 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).
*
* @see [Modules](https://docs.nestjs.com/modules)
*
* @usageNotes
* The following example:
* - declares `CatsController` as a controller to be instantiated when the
* `CatsModule` is bootstrapped
* - declares `CatsService` as a provider that can be injected within the
* module scope of the `CatsModule`
* - exports `CatsService` so that any module that imports `CatsModule`
* may inject `CatsService`
*
* ```typescript
* import { Module } from '@nestjs/common';
* import { CatsController } from './cats.controller';
* import { CatsService } from './cats.service';
*
* @Module({
* controllers: [CatsController],
* providers: [CatsService],
* exports: [CatsService]
* })
* export class CatsModule {}
* ```
*
* @publicApi
*/
export function Module(metadata: ModuleMetadata): ClassDecorator {
const propsKeys = Object.keys(metadata);

View File

@@ -43,6 +43,7 @@ export {
WebSocketAdapter,
WsExceptionFilter,
WsMessageHandler,
ScopeOptions,
} from './interfaces';
export * from './pipes';
export * from './serializer';

View File

@@ -1,4 +1,8 @@
/**
* Set origin to a function implementing some custom logic. The function takes the
* request origin as the first parameter and a callback (which expects the signature
* err [object], allow [bool]) as the second.
*
* @see https://github.com/expressjs/cors
*/
export type CustomOrigin = (
@@ -6,13 +10,42 @@ export type CustomOrigin = (
callback: (err: Error | null, allow?: boolean) => void,
) => void;
/**
* @publicApi
*
* @see https://github.com/expressjs/cors
*/
export interface CorsOptions {
/**
* Configures the `Access-Control-Allow-Origins` CORS header. See [here for more detail.](https://github.com/expressjs/cors#configuration-options)
*/
origin?: boolean | string | RegExp | (string | RegExp)[] | CustomOrigin;
/**
* Configures the Access-Control-Allow-Methods CORS header
*/
methods?: string | string[];
/**
* Configures the Access-Control-Allow-Headers CORS header.
*/
allowedHeaders?: string | string[];
/**
* Configures the Access-Control-Expose-Headers CORS header.
*/
exposedHeaders?: string | string[];
/**
* Configures the Access-Control-Allow-Credentials CORS header.
*/
credentials?: boolean;
/**
* Configures the Access-Control-Max-Age CORS header.
*/
maxAge?: number;
/**
* Whether to pass the CORS preflight response to the next handler?
*/
preflightContinue?: boolean;
/**
* Provides a status code to use for successful OPTIONS requests.
*/
optionsSuccessStatus?: number;
}

View File

@@ -1,23 +1,74 @@
/**
* Methods to obtain request and response objects.
*/
export interface HttpArgumentsHost {
/**
* Returns the in-flight `request` object.
*/
getRequest<T = any>(): T;
/**
* Returns the in-flight `response` object.
*/
getResponse<T = any>(): T;
getNext<T = any>(): T;
}
/**
* Methods to obtain WebSocket data and client objects.
*/
export interface WsArgumentsHost {
/**
* Returns the data object.
*/
getData<T = any>(): T;
/**
* Returns the client object.
*/
getClient<T = any>(): T;
}
/**
* Methods to obtain RPC data object.
*/
export interface RpcArgumentsHost {
/**
* Returns the data object.
*/
getData<T = any>(): T;
}
/**
* @publicApi
*
* @description
* 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.
*
*/
export interface ArgumentsHost {
/**
* Returns the array of arguments being passed to the handler.
*/
getArgs<T extends Array<any> = any[]>(): T;
/**
* Returns a particular argument by index.
* @param index
*/
getArgByIndex<T = any>(index: number): T;
/**
* Switch context to RPC
* @returns interface with methods to retrieve RPC arguments
*/
switchToRpc(): RpcArgumentsHost;
/**
* Switch context to HTTP
* @returns interface with methods to retrieve HTTP arguments
*/
switchToHttp(): HttpArgumentsHost;
/**
* Switch context to WebSockets
* @returns interface with methods to retrieve WebSockets arguments
*/
switchToWs(): WsArgumentsHost;
}

View File

@@ -1,7 +1,25 @@
import { Observable } from 'rxjs';
import { ExecutionContext } from './execution-context.interface';
/**
* @publicApi
*
* @description
* 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` or `Observable`).
*
* @see [Guards](https://docs.nestjs.com/guards)
*/
export interface CanActivate {
/**
* @param 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.
*/
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean>;

View File

@@ -1,7 +1,22 @@
import { Type } from '../index';
import { ArgumentsHost } from './arguments-host.interface';
/**
* @publicApi
*
* @description
* Details about the current request pipeline.
*
* @see [Execution Context](https://docs.nestjs.com/guards#execution-context)
*/
export interface ExecutionContext extends ArgumentsHost {
/**
* Returns the *type* of the controller class which the current handler belongs to.
*/
getClass<T = any>(): Type<T>;
/**
* Returns a reference to the handler (method) that will be invoked next in the
* request pipeline.
*/
getHandler(): Function;
}

View File

@@ -1,6 +1,18 @@
import { ModuleMetadata } from './module-metadata.interface';
import { Type } from '../type.interface';
/**
* @publicApi
*
* @description
*
* Interface defining a Dynamic Module.
*
* @see [Dynamic Modules](https://docs.nestjs.com/modules#dynamic-modules)
*/
export interface DynamicModule extends ModuleMetadata {
/**
* A module
*/
module: Type<any>;
}

View File

@@ -4,12 +4,37 @@ import { DynamicModule } from './dynamic-module.interface';
import { ForwardReference } from './forward-reference.interface';
import { Provider } from './provider.interface';
/**
* @publicApi
*
* @description
*
* Interface defining the property object that describes the module.
*
* @see [Modules](https://docs.nestjs.com/modules)
*/
export interface ModuleMetadata {
/**
* Optional list of imported modules that export the providers which are
* required in this module.
*/
imports?: Array<
Type<any> | DynamicModule | Promise<DynamicModule> | ForwardReference
>;
/**
* Optional list of controllers defined in this module which have to be
* instantiated.
*/
controllers?: Type<any>[];
/**
* Optional list of providers that will be instantiated by the Nest injector
* and that may be shared at least across this module.
*/
providers?: Provider[];
/**
* Optional list of the subset of providers that are provided by this module
* and should be available in other modules which import this module.
*/
exports?: Array<
| DynamicModule
| Promise<DynamicModule>

View File

@@ -1,3 +1,13 @@
/**
* @publicApi
*
* @description
* Interface defining method called just before Nest destroys the host module
* (`app.close()` method has been evaluated). Use to perform cleanup on
* resources (e.g., Database connections).
*
* @see [Lifecycle Events](https://docs.nestjs.com/fundamentals/lifecycle-events)
*/
export interface OnModuleDestroy {
onModuleDestroy(): any;
}

View File

@@ -1,3 +1,11 @@
/**
* @publicApi
*
* @description
* Interface defining method called once the host module has been initialized.
*
* @see [Lifecycle Events](https://docs.nestjs.com/fundamentals/lifecycle-events)
*/
export interface OnModuleInit {
onModuleInit(): any;
}

View File

@@ -1,5 +1,11 @@
import { LoggerService } from '../services/logger.service';
/**
* @publicApi
*/
export class NestApplicationContextOptions {
/**
* specify the logger to use
*/
logger?: LoggerService | boolean;
}

View File

@@ -3,6 +3,12 @@ import { LoggerService } from '../services/logger.service';
import { Abstract } from './abstract.interface';
import { Type } from './type.interface';
/**
* @publicApi
*
* @description
* Interface defining NestApplicationContext.
*/
export interface INestApplicationContext {
/**
* Allows navigating through the modules tree, for example, to pull out a specific instance from the selected module.

View File

@@ -1,9 +1,21 @@
import { CorsOptions } from './external/cors-options.interface';
import { HttpsOptions } from './external/https-options.interface';
import { NestApplicationContextOptions } from './nest-application-context-options.interface';
import { CorsOptions } from './external/cors-options.interface';
/**
* @publicApi
*/
export interface NestApplicationOptions extends NestApplicationContextOptions {
/**
* CORS options from [CORS package](https://github.com/expressjs/cors#configuration-options)
*/
cors?: boolean | CorsOptions;
/**
* Whether to use underlying platform body parser.
*/
bodyParser?: boolean;
/**
* Set of configurable HTTPS options
*/
httpsOptions?: HttpsOptions;
}

View File

@@ -7,6 +7,12 @@ import { MicroserviceOptions } from './microservices/microservice-configuration.
import { INestApplicationContext } from './nest-application-context.interface';
import { WebSocketAdapter } from './websockets/web-socket-adapter.interface';
/**
* @publicApi
*
* @description
* Interface defining the core NestApplication object.
*/
export interface INestApplication extends INestApplicationContext {
/**
* A wrapper function around HTTP adapter method: `adapter.use()`.
@@ -29,7 +35,7 @@ export interface INestApplication extends INestApplicationContext {
* @param {number} port
* @param {string} hostname
* @param {Function} callback Optional callback
* @returns {Promise}
* @returns A Promise that, when resolved, is a reference to the underlying HttpServer.
*/
listen(port: number | string, callback?: () => void): Promise<any>;
listen(
@@ -48,16 +54,16 @@ export interface INestApplication extends INestApplicationContext {
listenAsync(port: number | string, hostname?: string): Promise<any>;
/**
* Registers the prefix for the every HTTP route path
* Registers a prefix for every HTTP route path.
*
* @param {string} prefix The prefix for the every HTTP route path (for example `/v1/api`)
* @param {string} prefix The prefix for every HTTP route path (for example `/v1/api`)
* @returns {void}
*/
setGlobalPrefix(prefix: string): this;
/**
* Setup Ws Adapter which will be used inside Gateways.
* Use, when you want to override default `socket.io` library.
* Use when you want to override default `socket.io` library.
*
* @param {WebSocketAdapter} adapter
* @returns {void}
@@ -65,7 +71,8 @@ export interface INestApplication extends INestApplicationContext {
useWebSocketAdapter(adapter: WebSocketAdapter): this;
/**
* Connects microservice to the NestApplication instance. Transforms application to the hybrid instance.
* Connects microservice to the NestApplication instance. Transforms application
* to a hybrid instance.
*
* @param {MicroserviceOptions} options Microservice options object
* @returns {INestMicroservice}
@@ -80,21 +87,21 @@ export interface INestApplication extends INestApplicationContext {
getMicroservices(): INestMicroservice[];
/**
* Returns an underlying, native HTTP server.
* Returns the underlying native HTTP server.
*
* @returns {http.Server}
*/
getHttpServer(): any;
/**
* Returns an underlying HTTP adapter.
* Returns the underlying HTTP adapter.
*
* @returns {HttpServer}
*/
getHttpAdapter(): HttpServer;
/**
* Starts all connected microservices asynchronously
* Starts all connected microservices asynchronously.
*
* @param {Function} callback Optional callback function
* @returns {void}
@@ -102,42 +109,45 @@ export interface INestApplication extends INestApplicationContext {
startAllMicroservices(callback?: () => void): this;
/**
* Starts all connected microservices and can be awaited
* Starts all connected microservices and can be awaited.
*
* @returns {Promise}
*/
startAllMicroservicesAsync(): Promise<void>;
/**
* Registers exception filters as a global filters (will be used within every HTTP route handler)
* Registers exception filters as global filters (will be used within
* every HTTP route handler)
*
* @param {ExceptionFilter[]} ...filters
*/
useGlobalFilters(...filters: ExceptionFilter[]): this;
/**
* Registers pipes as a global pipes (will be used within every HTTP route handler)
* Registers pipes as global pipes (will be used within every HTTP route handler)
*
* @param {PipeTransform[]} ...pipes
*/
useGlobalPipes(...pipes: PipeTransform<any>[]): this;
/**
* Registers interceptors as a global interceptors (will be used within every HTTP route handler)
* Registers interceptors as global interceptors (will be used within
* every HTTP route handler)
*
* @param {NestInterceptor[]} ...interceptors
*/
useGlobalInterceptors(...interceptors: NestInterceptor[]): this;
/**
* Registers guards as a global guards (will be used within every HTTP route handler)
* Registers guards as global guards (will be used within every HTTP route handler)
*
* @param {CanActivate[]} ...guards
*/
useGlobalGuards(...guards: CanActivate[]): this;
/**
* Terminates the application (including NestApplication, Gateways, and each connected microservice)
* Terminates the application (including NestApplication, Gateways, and each connected
* microservice)
*
* @returns {Promise<void>}
*/

View File

@@ -1,3 +1,12 @@
/**
* @publicApi
*
* @description
* Interface defining method called once the application has fully started and
* is bootstrapped.
*
* @see [Lifecycle Events](https://docs.nestjs.com/fundamentals/lifecycle-events)
*/
export interface OnApplicationBootstrap {
onApplicationBootstrap(): any;
}

View File

@@ -1,3 +1,12 @@
/**
* @publicApi
*
* @description
* Interface defining method to respond to system signals (when application gets
* shutdown by, e.g., SIGTERM)
*
* @see [Lifecycle Events](https://docs.nestjs.com/fundamentals/lifecycle-events)
*/
export interface OnApplicationShutdown {
onApplicationShutdown(signal?: string): any;
}

View File

@@ -1,9 +1,31 @@
/**
* @publicApi
*/
export enum Scope {
/**
* The provider can be shared across multiple classes. The provider lifetime
* is strictly tied to the application lifecycle. Once the application has
* bootstrapped, all providers have been instantiated.
*/
DEFAULT,
/**
* A new private instance of the provider is instantiated for every use
*/
TRANSIENT,
/**
* A new instance is instantiated for each request processing pipeline
*/
REQUEST,
}
/**
* @publicApi
*
* @see [Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes)
*/
export interface ScopeOptions {
/**
* Specifies the lifetime of an injected Provider or Controller.
*/
scope?: Scope;
}

1
packages/core/PACKAGE.md Normal file
View File

@@ -0,0 +1 @@
Implements Nest core functionalities, low-level services, and utilities.

View File

@@ -3,6 +3,13 @@ import { RequestHandler } from '@nestjs/common/interfaces';
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface';
/**
* @publicApi
*
* @description
*
* This is the AbstractHttpAdapter
*/
export abstract class AbstractHttpAdapter<
TServer = any,
TRequest = any,

View File

@@ -19,6 +19,9 @@ import { ContainerScanner } from './injector/container-scanner';
import { Module } from './injector/module';
import { ModuleTokenFactory } from './injector/module-token-factory';
/**
* @publicApi
*/
export class NestApplicationContext implements INestApplicationContext {
private readonly moduleTokenFactory = new ModuleTokenFactory();
private readonly containerScanner: ContainerScanner;

View File

@@ -32,6 +32,9 @@ const { SocketModule } =
const { MicroservicesModule } =
optional('@nestjs/microservices/microservices-module') || ({} as any);
/**
* @publicApi
*/
export class NestApplication extends NestApplicationContext
implements INestApplication {
private readonly logger = new Logger(NestApplication.name, true);

View File

@@ -23,16 +23,35 @@ import { NestApplication } from './nest-application';
import { NestApplicationContext } from './nest-application-context';
import { DependenciesScanner } from './scanner';
/**
* @publicApi
*/
export class NestFactoryStatic {
private readonly logger = new Logger('NestFactory', true);
/**
* Creates an instance of the NestApplication
* @returns {Promise}
* Creates an instance of NestApplication.
*
* @param module Entry (root) application module class
* @param options List of options to initialize NestApplication
*
* @returns A promise that, when resolved,
* contains a reference to the NestApplication instance.
*/
public async create<T extends INestApplication = INestApplication>(
module: any,
options?: NestApplicationOptions,
): Promise<T>;
/**
* Creates an instance of NestApplication with the specified `httpAdapter`
*
* @param module Entry (root) application module class
* @param httpAdapter Adapter to proxy the request/response cycle to
* the underlying HTTP server
* @param options List of options to initialize NestApplication
*
* @returns A promise that, when resolved,
* contains a reference to the NestApplication instance.
*/
public async create<T extends INestApplication = INestApplication>(
module: any,
httpAdapter: AbstractHttpAdapter,
@@ -65,11 +84,13 @@ export class NestFactoryStatic {
}
/**
* Creates an instance of the NestMicroservice
* Creates an instance of NestMicroservice
*
* @param {} module Entry (root) application module class
* @param {NestMicroserviceOptions & MicroserviceOptions} options Optional microservice configuration
* @returns {Promise}
* @param module Entry (root) application module class
* @param options Optional microservice configuration
*
* @returns A promise that, when resolved,
* contains a reference to the NestMicroservice instance.
*/
public async createMicroservice(
module: any,
@@ -92,11 +113,13 @@ export class NestFactoryStatic {
}
/**
* Creates an instance of the NestApplicationContext
* Creates an instance of NestApplicationContext
*
* @param {} module Entry (root) application module class
* @param {NestApplicationContextOptions} options Optional Nest application configuration
* @returns {Promise}
* @param module Entry (root) application module class
* @param options Optional Nest application configuration
*
* @returns A promise that, when resolved,
* contains a reference to the NestApplicationContext instance.
*/
public async createApplicationContext(
module: any,
@@ -213,4 +236,49 @@ export class NestFactoryStatic {
}
}
/**
* @publicApi
*
* @description
*
* Use NestFactory to create an application instance.
*
* @usageNotes
*
* ### [Any Application] Specifying an entry module
* Pass the required *root module* for the application via the module parameter.
* By convention, it is usually called `ApplicationModule`. Starting with this
* module, Nest assembles the dependency graph and begins the process of
* Dependency Injection and instantiates the classes needed to launch your
* application.
*
* ```typescript
* import { NestFactory } from '@nestjs/core';
* import { ApplicationModule } from './app.module';
*
* async function bootstrap() {
* const app = await NestFactory.create(ApplicationModule);
* await app.listen(3000);
* }
* bootstrap();
* ```
*
* ### [NestApplication only] Providing an httpAdapter object
* In this example, we create a NestApplication that uses the `FastifyAdapter`.
* Pass options to `Fastify` by passing an options object into the
* `FastifyAdapter()` constructor. Note that if the `httpAdapter` is not
* `Express`, the supporting package (e.g., `@nestjs/platform-fastify`) must be
* installed.
*
* ```typescript
* async function bootstrap() {
* const app = await NestFactory.create<NestFastifyApplication>(
* ApplicationModule,
* new FastifyAdapter(),
* );
* await app.listen(3000);
* }
* bootstrap();
* ```
*/
export const NestFactory = new NestFactoryStatic();

View File

@@ -1,6 +1,14 @@
import { INestApplication } from '@nestjs/common';
import { ServeStaticOptions } from './serve-static-options.interface';
/**
* @publicApi
*
* @description
* Interface describing methods on NestExpressApplication.
*
* @see [Platform](https://docs.nestjs.com/first-steps#platform)
*/
export interface NestExpressApplication extends INestApplication {
/**
* A wrapper function around native `express.set()` method.

View File

@@ -1,5 +1,11 @@
/**
* @see https://www.npmjs.com/package/@types/serve-static
* @publicApi
*
* @description
* Interface describing options for serving static assets.
*
* @see [Serving static files in Express](https://expressjs.com/en/starter/static-files.html)
* @see [Model-View-Controller](https://docs.nestjs.com/techniques/mvc)
*/
export interface ServeStaticOptions {
/**
@@ -60,10 +66,10 @@ export interface ServeStaticOptions {
/**
* Function to set custom headers on response. Alterations to the headers need to occur synchronously.
* The function is called as fn(res, path, stat), where the arguments are:
* res the response object
* path the file path that is being sent
* stat the stat object of the file that is being sent
* The function is called as `fn(res, path, stat)`, where the arguments are:
* `res` - the response object
* `path` - the file path that is being sent
* `stat` - the stat object of the file that is being sent
*/
setHeaders?: (res: any, path: string, stat: any) => any;

View File

@@ -5,4 +5,4 @@ export const source = 'packages';
export const integrationPath = 'integration';
export const samplePath = 'sample';
export const packagePaths = getDirs(source);
export const packagePaths = getDirs(source);