Merge branch '5.2.0' into chore/add-nodejs-10

This commit is contained in:
Kamil Myśliwiec
2018-07-25 19:56:49 +02:00
committed by GitHub
413 changed files with 58125 additions and 5279 deletions

41
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,41 @@
## PR Checklist
Please check if your PR fulfills the following requirements:
- [ ] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
- [ ] Tests for the changes have been added (for bug fixes / features)
- [ ] Docs have been added / updated (for bug fixes / features)
## PR Type
What kind of change does this PR introduce?
<!-- Please check the one that applies to this PR using "x". -->
```
[ ] Bugfix
[ ] Feature
[ ] Code style update (formatting, local variables)
[ ] Refactoring (no functional changes, no api changes)
[ ] Build related changes
[ ] CI related changes
[ ] Other... Please describe:
```
## What is the current behavior?
<!-- Please describe the current behavior that you are modifying, or link to a relevant issue. -->
Issue Number: N/A
## What is the new behavior?
## Does this PR introduce a breaking change?
```
[ ] Yes
[ ] No
```
<!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. -->
## Other information

1
.gitignore vendored
View File

@@ -1,6 +1,5 @@
# dependencies
node_modules/
package-lock.json
# IDE
/.idea

View File

@@ -1,16 +1,23 @@
language: node_js
node_js:
- "8"
- "9"
- "10"
- "8"
- "9"
- "10"
cache:
directories:
- "node_modules"
git:
depth: 5
addons:
firefox: "latest"
firefox: "latest"
before_script:
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start
before_install:
- npm i -g npm@latest
install:
- npm install
- gulp build
- npm ci
- gulp build
script:
- npm test
- npm test
after_success: npm run coverage

View File

@@ -183,10 +183,10 @@ Footer should contain a [closing reference to an issue](https://help.github.com/
Samples: (even more [samples](https://github.com/nestjs/nest/commits/master))
```
docs(changelog): update change log to beta.5
docs(changelog) update change log to beta.5
```
```
fix(release): need to depend on latest rxjs and zone.js
bugfix(@nestjs/core) need to depend on latest rxjs and zone.js
The version in our package.json gets copied to the one we publish, and users need the latest of these.
```
@@ -200,8 +200,8 @@ Must be one of the following:
* **build**: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
* **ci**: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
* **docs**: Documentation only changes
* **feat**: A new feature
* **fix**: A bug fix
* **feature**: A new feature
* **bugfix**: A bug fix
* **perf**: A code change that improves performance
* **refactor**: A code change that neither fixes a bug nor adds a feature
* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
@@ -214,7 +214,7 @@ The following is the list of supported scopes:
* **common**
* **core**
* **examples**
* **sample**
* **microservices**
* **testing**
* **websockets**
@@ -223,7 +223,7 @@ There are currently a few exceptions to the "use package name" rule:
* **packaging**: used for changes that change the npm package layout in all of our packages, e.g. public path changes, package.json changes done to all packages, d.ts file/format changes, changes to bundles, etc.
* **changelog**: used for updating the release notes in CHANGELOG.md
* **examples/#**: for the example apps directory, replacing # with the example app number
* **sample/#**: for the example apps directory, replacing # with the example app number
<!-- * **aio**: used for docs-app (angular.io) related changes within the /aio directory of the repo -->
* none/empty string: useful for `style`, `test` and `refactor` changes that are done across all packages (e.g. `style: add missing semicolons`)

View File

@@ -37,7 +37,8 @@
## Getting started
To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books:
* To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books:
* 要查看中文 [指南](readme_zh.md), 请访问 [docs.nestjs.cn](https://docs.nestjs.cn). :books:
## Support
@@ -47,56 +48,17 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="300" /></a>
#### Silver Sponsors
<a href="https://neoteric.eu/"><img src="https://nestjs.com/img/neoteric-cut.png" width="130" /></a> &nbsp; <a href="https://www.swingdev.io"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="160" /></a>
#### Sponsors
<a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.svg" width="150" /></a> &nbsp; <a href="https://www.swingdev.io"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="150" /></a>
<a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.svg" width="120" /></a> &nbsp; <a href="http://angularity.io"><img src="http://angularity.io/media/logo.svg" height="32" /></a> &nbsp; <a href="http://gojob.com"><img src="https://gojob.com/w/wp-content/uploads/2017/02/cropped-Logo-web-home.png" height="44" /> &nbsp; <a href="https://keycdn.com"><img src="https://nestjs.com/img/keycdn.svg" height="37" /></a> &nbsp; <a href="https://hostpresto.com"><img src="https://nestjs.com/img/hostpresto.png" height="32" /></a>
## Backers
<a href="https://opencollective.com/nest/backer/0/website" target="_blank"><img src="https://opencollective.com/nest/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/1/website" target="_blank"><img src="https://opencollective.com/nest/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/2/website" target="_blank"><img src="https://opencollective.com/nest/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/3/website" target="_blank"><img src="https://opencollective.com/nest/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/4/website" target="_blank"><img src="https://opencollective.com/nest/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/5/website" target="_blank"><img src="https://opencollective.com/nest/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/6/website" target="_blank"><img src="https://opencollective.com/nest/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/7/website" target="_blank"><img src="https://opencollective.com/nest/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/8/website" target="_blank"><img src="https://opencollective.com/nest/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/9/website" target="_blank"><img src="https://opencollective.com/nest/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/10/website" target="_blank"><img src="https://opencollective.com/nest/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/11/website" target="_blank"><img src="https://opencollective.com/nest/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/12/website" target="_blank"><img src="https://opencollective.com/nest/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/13/website" target="_blank"><img src="https://opencollective.com/nest/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/14/website" target="_blank"><img src="https://opencollective.com/nest/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/15/website" target="_blank"><img src="https://opencollective.com/nest/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/16/website" target="_blank"><img src="https://opencollective.com/nest/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/17/website" target="_blank"><img src="https://opencollective.com/nest/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/18/website" target="_blank"><img src="https://opencollective.com/nest/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/19/website" target="_blank"><img src="https://opencollective.com/nest/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/20/website" target="_blank"><img src="https://opencollective.com/nest/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/21/website" target="_blank"><img src="https://opencollective.com/nest/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/22/website" target="_blank"><img src="https://opencollective.com/nest/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/23/website" target="_blank"><img src="https://opencollective.com/nest/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/24/website" target="_blank"><img src="https://opencollective.com/nest/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/25/website" target="_blank"><img src="https://opencollective.com/nest/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/26/website" target="_blank"><img src="https://opencollective.com/nest/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/27/website" target="_blank"><img src="https://opencollective.com/nest/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/28/website" target="_blank"><img src="https://opencollective.com/nest/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/29/website" target="_blank"><img src="https://opencollective.com/nest/backer/29/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/30/website" target="_blank"><img src="https://opencollective.com/nest/backer/30/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/31/website" target="_blank"><img src="https://opencollective.com/nest/backer/31/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/32/website" target="_blank"><img src="https://opencollective.com/nest/backer/32/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/33/website" target="_blank"><img src="https://opencollective.com/nest/backer/33/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/34/website" target="_blank"><img src="https://opencollective.com/nest/backer/34/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/35/website" target="_blank"><img src="https://opencollective.com/nest/backer/35/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/36/website" target="_blank"><img src="https://opencollective.com/nest/backer/36/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/37/website" target="_blank"><img src="https://opencollective.com/nest/backer/37/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/38/website" target="_blank"><img src="https://opencollective.com/nest/backer/38/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/39/website" target="_blank"><img src="https://opencollective.com/nest/backer/39/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/40/website" target="_blank"><img src="https://opencollective.com/nest/backer/40/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/41/website" target="_blank"><img src="https://opencollective.com/nest/backer/41/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/42/website" target="_blank"><img src="https://opencollective.com/nest/backer/42/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/43/website" target="_blank"><img src="https://opencollective.com/nest/backer/43/avatar.svg"></a>
<a href="https://opencollective.com/nest"><img src="https://opencollective.com/nest/backers.svg?width=890"></a>
## Stay in touch
@@ -107,5 +69,3 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
## License
Nest is [MIT licensed](LICENSE).
<h4 align="center"> <a href="readme_zh.md">中文说明</a></h4>

View File

@@ -14,7 +14,7 @@
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://api.travis-ci.org/nestjs/nest.svg?branch=master" alt="Travis" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://img.shields.io/travis/nestjs/nest/master.svg?label=linux" alt="Linux" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#6" alt="Coverage" /></a>
<a href="https://gitter.im/nestjs/nestjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=body_badge"><img src="https://badges.gitter.im/nestjs/nestjs.svg" alt="Gitter" /></a>
<a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
@@ -37,7 +37,8 @@
## Getting started
To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books:
* To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books:
* 要查看中文 [指南](readme_zh.md), 请访问 [docs.nestjs.cn](https://docs.nestjs.cn). :books:
## Support
@@ -47,56 +48,17 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="300" /></a>
#### Silver Sponsors
<a href="https://neoteric.eu/"><img src="https://nestjs.com/img/neoteric-cut.png" width="130" /></a> &nbsp; <a href="https://www.swingdev.io"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="160" /></a>
#### Sponsors
<a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.svg" width="150" /></a> &nbsp; <a href="https://www.swingdev.io"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="150" /></a>
<a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.svg" width="120" /></a> &nbsp; <a href="http://angularity.io"><img src="http://angularity.io/media/logo.svg" height="32" /></a> &nbsp; <a href="http://gojob.com"><img src="https://gojob.com/w/wp-content/uploads/2017/02/cropped-Logo-web-home.png" height="44" /> &nbsp; <a href="https://keycdn.com"><img src="https://nestjs.com/img/keycdn.svg" height="37" /></a> &nbsp; <a href="https://hostpresto.com"><img src="https://nestjs.com/img/hostpresto.png" height="32" /></a>
## Backers
<a href="https://opencollective.com/nest/backer/0/website" target="_blank"><img src="https://opencollective.com/nest/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/1/website" target="_blank"><img src="https://opencollective.com/nest/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/2/website" target="_blank"><img src="https://opencollective.com/nest/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/3/website" target="_blank"><img src="https://opencollective.com/nest/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/4/website" target="_blank"><img src="https://opencollective.com/nest/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/5/website" target="_blank"><img src="https://opencollective.com/nest/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/6/website" target="_blank"><img src="https://opencollective.com/nest/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/7/website" target="_blank"><img src="https://opencollective.com/nest/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/8/website" target="_blank"><img src="https://opencollective.com/nest/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/9/website" target="_blank"><img src="https://opencollective.com/nest/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/10/website" target="_blank"><img src="https://opencollective.com/nest/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/11/website" target="_blank"><img src="https://opencollective.com/nest/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/12/website" target="_blank"><img src="https://opencollective.com/nest/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/13/website" target="_blank"><img src="https://opencollective.com/nest/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/14/website" target="_blank"><img src="https://opencollective.com/nest/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/15/website" target="_blank"><img src="https://opencollective.com/nest/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/16/website" target="_blank"><img src="https://opencollective.com/nest/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/17/website" target="_blank"><img src="https://opencollective.com/nest/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/18/website" target="_blank"><img src="https://opencollective.com/nest/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/19/website" target="_blank"><img src="https://opencollective.com/nest/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/20/website" target="_blank"><img src="https://opencollective.com/nest/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/21/website" target="_blank"><img src="https://opencollective.com/nest/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/22/website" target="_blank"><img src="https://opencollective.com/nest/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/23/website" target="_blank"><img src="https://opencollective.com/nest/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/24/website" target="_blank"><img src="https://opencollective.com/nest/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/25/website" target="_blank"><img src="https://opencollective.com/nest/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/26/website" target="_blank"><img src="https://opencollective.com/nest/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/27/website" target="_blank"><img src="https://opencollective.com/nest/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/28/website" target="_blank"><img src="https://opencollective.com/nest/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/29/website" target="_blank"><img src="https://opencollective.com/nest/backer/29/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/30/website" target="_blank"><img src="https://opencollective.com/nest/backer/30/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/31/website" target="_blank"><img src="https://opencollective.com/nest/backer/31/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/32/website" target="_blank"><img src="https://opencollective.com/nest/backer/32/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/33/website" target="_blank"><img src="https://opencollective.com/nest/backer/33/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/34/website" target="_blank"><img src="https://opencollective.com/nest/backer/34/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/35/website" target="_blank"><img src="https://opencollective.com/nest/backer/35/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/36/website" target="_blank"><img src="https://opencollective.com/nest/backer/36/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/37/website" target="_blank"><img src="https://opencollective.com/nest/backer/37/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/38/website" target="_blank"><img src="https://opencollective.com/nest/backer/38/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/39/website" target="_blank"><img src="https://opencollective.com/nest/backer/39/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/40/website" target="_blank"><img src="https://opencollective.com/nest/backer/40/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/41/website" target="_blank"><img src="https://opencollective.com/nest/backer/41/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/42/website" target="_blank"><img src="https://opencollective.com/nest/backer/42/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/43/website" target="_blank"><img src="https://opencollective.com/nest/backer/43/avatar.svg"></a>
<a href="https://opencollective.com/nest"><img src="https://opencollective.com/nest/backers.svg?width=890"></a>
## Stay in touch
@@ -107,5 +69,3 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
## License
Nest is [MIT licensed](LICENSE).
<h4 align="center"> <a href="readme_zh.md">中文说明</a></h4>

View File

@@ -1,5 +1,5 @@
/**
* Assigns the metadata to the class / function under specified `key`.
* Assigns the metadata to the class/function under specified `key`.
* This metadata can be reflected using `Reflector` class.
*/
export declare const ReflectMetadata: (metadataKey: any, metadataValue: any) => (target: object, key?: any, descriptor?: any) => any;

View File

@@ -1,7 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Assigns the metadata to the class / function under specified `key`.
* Assigns the metadata to the class/function under specified `key`.
* This metadata can be reflected using `Reflector` class.
*/
exports.ReflectMetadata = (metadataKey, metadataValue) => (target, key, descriptor) => {

View File

@@ -1,13 +1,14 @@
import { CustomParamFactory } from '../../interfaces/features/custom-route-param-factory.interface';
import { PipeTransform } from '../../index';
import { Type } from '../../interfaces';
import { CustomParamFactory } from '../../interfaces/features/custom-route-param-factory.interface';
/**
* Creates HTTP route param decorator
* Defines HTTP route param decorator
* @param factory
*/
export declare function createParamDecorator(factory: CustomParamFactory): (data?: any, ...pipes: PipeTransform<any>[]) => ParameterDecorator;
export declare function createParamDecorator(factory: CustomParamFactory): (data?: any, ...pipes: (Type<PipeTransform> | PipeTransform)[]) => ParameterDecorator;
/**
* Creates HTTP route param decorator
* Defines HTTP route param decorator
* @deprecated
* @param factory
*/
export declare function createRouteParamDecorator(factory: CustomParamFactory): (data?: any, ...pipes: PipeTransform<any>[]) => ParameterDecorator;
export declare function createRouteParamDecorator(factory: CustomParamFactory): (data?: any, ...pipes: (Type<PipeTransform> | PipeTransform)[]) => ParameterDecorator;

View File

@@ -12,7 +12,7 @@ const randomString = () => Math.random()
.toString(36)
.substring(2, 15);
/**
* Creates HTTP route param decorator
* Defines HTTP route param decorator
* @param factory
*/
function createParamDecorator(factory) {
@@ -24,7 +24,7 @@ function createParamDecorator(factory) {
}
exports.createParamDecorator = createParamDecorator;
/**
* Creates HTTP route param decorator
* Defines HTTP route param decorator
* @deprecated
* @param factory
*/

View File

@@ -12,7 +12,7 @@ export declare const Request: () => ParameterDecorator;
export declare const Response: () => ParameterDecorator;
export declare const Next: () => ParameterDecorator;
export declare const Session: () => ParameterDecorator;
export declare const UploadedFile: () => ParameterDecorator;
export declare const UploadedFile: (fileKey?: string) => ParameterDecorator;
export declare const UploadedFiles: () => ParameterDecorator;
export declare const Headers: (property?: string) => ParameterDecorator;
export declare function Query(): any;

View File

@@ -8,4 +8,5 @@ export declare class HttpService {
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
readonly axiosRef: any;
}

View File

@@ -19,10 +19,13 @@ class HttpService {
return rxjs_1.from(axios_1.default.post(url, data, config));
}
put(url, data, config) {
return rxjs_1.from(axios_1.default.post(url, data, config));
return rxjs_1.from(axios_1.default.put(url, data, config));
}
patch(url, data, config) {
return rxjs_1.from(axios_1.default.post(url, data, config));
return rxjs_1.from(axios_1.default.patch(url, data, config));
}
get axiosRef() {
return axios_1.default;
}
}
exports.HttpService = HttpService;

View File

@@ -1,6 +1,6 @@
export * from './decorators';
export * from './enums';
export { NestModule, INestApplication, INestMicroservice, NestMiddleware, MiddlewareFunction, MiddlewareConsumer, OnModuleInit, ExceptionFilter, WebSocketAdapter, PipeTransform, Paramtype, ArgumentMetadata, OnModuleDestroy, ExecutionContext, CanActivate, RpcExceptionFilter, WsExceptionFilter, NestInterceptor, DynamicModule, INestApplicationContext, HttpServer, HttpServerFactory, ArgumentsHost, INestExpressApplication, INestFastifyApplication } from './interfaces';
export { NestModule, INestApplication, INestMicroservice, NestMiddleware, MiddlewareFunction, MiddlewareConsumer, OnModuleInit, ExceptionFilter, WebSocketAdapter, PipeTransform, Paramtype, ArgumentMetadata, OnModuleDestroy, ExecutionContext, CanActivate, RpcExceptionFilter, WsExceptionFilter, NestInterceptor, DynamicModule, INestApplicationContext, HttpServer, Provider, Type, HttpServerFactory, ArgumentsHost, INestExpressApplication, INestFastifyApplication, ForwardReference } from './interfaces';
export * from './interceptors';
export * from './services/logger.service';
export * from './pipes';

View File

@@ -0,0 +1,9 @@
import { Observable } from 'rxjs';
import { ExecutionContext } from '../interfaces';
import { MulterField, MulterOptions } from '../interfaces/external/multer-options.interface';
export declare function FileFieldsInterceptor(uploadFields: MulterField[], options?: MulterOptions): {
new (): {
readonly upload: any;
intercept(context: ExecutionContext, call$: Observable<any>): Promise<Observable<any>>;
};
};

View File

@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const multer = require("multer");
const multer_utils_1 = require("./multer/multer.utils");
function FileFieldsInterceptor(uploadFields, options) {
const Interceptor = class {
constructor() {
this.upload = multer(options);
}
async intercept(context, call$) {
const ctx = context.switchToHttp();
await new Promise((resolve, reject) => this.upload.fields(uploadFields)(ctx.getRequest(), ctx.getResponse(), err => {
if (err) {
const error = multer_utils_1.transformException(err);
return reject(error);
}
resolve();
}));
return call$;
}
};
return Interceptor;
}
exports.FileFieldsInterceptor = FileFieldsInterceptor;

View File

@@ -1,12 +1,4 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const multer = require("multer");
const component_decorator_1 = require("../decorators/core/component.decorator");
@@ -16,18 +8,16 @@ function FileInterceptor(fieldName, options) {
constructor() {
this.upload = multer(options);
}
intercept(context, call$) {
return __awaiter(this, void 0, void 0, function* () {
const ctx = context.switchToHttp();
yield new Promise((resolve, reject) => this.upload.single(fieldName)(ctx.getRequest(), ctx.getResponse(), err => {
if (err) {
const error = multer_utils_1.transformException(err);
return reject(error);
}
resolve();
}));
return call$;
});
async intercept(context, call$) {
const ctx = context.switchToHttp();
await new Promise((resolve, reject) => this.upload.single(fieldName)(ctx.getRequest(), ctx.getResponse(), err => {
if (err) {
const error = multer_utils_1.transformException(err);
return reject(error);
}
resolve();
}));
return call$;
}
});
}

View File

@@ -1,12 +1,4 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const multer = require("multer");
const multer_utils_1 = require("./multer/multer.utils");
@@ -15,18 +7,16 @@ function FilesInterceptor(fieldName, maxCount, options) {
constructor() {
this.upload = multer(options);
}
intercept(context, call$) {
return __awaiter(this, void 0, void 0, function* () {
const ctx = context.switchToHttp();
yield new Promise((resolve, reject) => this.upload.array(fieldName, maxCount)(ctx.getRequest(), ctx.getResponse(), err => {
if (err) {
const error = multer_utils_1.transformException(err);
return reject(error);
}
resolve();
}));
return call$;
});
async intercept(context, call$) {
const ctx = context.switchToHttp();
await new Promise((resolve, reject) => this.upload.array(fieldName, maxCount)(ctx.getRequest(), ctx.getResponse(), err => {
if (err) {
const error = multer_utils_1.transformException(err);
return reject(error);
}
resolve();
}));
return call$;
}
};
return Interceptor;

View File

@@ -1,2 +1,3 @@
export * from './file-fields.interceptor';
export * from './file.interceptor';
export * from './files.interceptor';

View File

@@ -3,5 +3,6 @@ function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./file-fields.interceptor"));
__export(require("./file.interceptor"));
__export(require("./files.interceptor"));

View File

@@ -1,2 +1,2 @@
import { PayloadTooLargeException, BadRequestException } from './../../exceptions';
import { BadRequestException, PayloadTooLargeException } from './../../exceptions';
export declare function transformException(error: Error | undefined): Error | BadRequestException | PayloadTooLargeException;

View File

@@ -49,3 +49,9 @@ export interface MulterOptions {
buffer: Buffer;
}, callback: (error: Error | null, acceptFile: boolean) => void): void;
}
export interface MulterField {
/** The field name. */
name: string;
/** Optional maximum number of files per field to accept. */
maxCount?: number;
}

View File

@@ -39,4 +39,8 @@ export interface ValidatorOptions {
*/
value?: boolean;
};
/**
* Setting true will cause fail validation of unknown objects.
*/
forbidUnknownValues?: boolean;
}

View File

@@ -1 +1 @@
export declare type CustomParamFactory = (data, req) => any;
export declare type CustomParamFactory<TData = any, TRequest = any, TResult = any> = (data: TData, req: TRequest) => TResult;

View File

@@ -1,5 +1,6 @@
/// <reference types="node" />
import { IncomingMessage, ServerResponse } from 'http';
import { RequestMethod } from '../../enums';
export declare type ErrorHandler = (error: any, req: Partial<IncomingMessage>, res: ServerResponse | any, next?: Function) => any;
export declare type RequestHandler = (req: Partial<IncomingMessage>, res: ServerResponse | any, next?: Function) => any;
export interface HttpServer {
@@ -29,8 +30,10 @@ export interface HttpServer {
useStaticAssets?(...args: any[]): this;
setBaseViewsDir?(path: string): this;
setViewEngine?(engineOrOptions: any): this;
createMiddlewareFactory(method: RequestMethod): (path: string, callback: Function) => any;
getRequestMethod?(request: any): string;
getRequestUrl?(request: any): string;
getInstance(): any;
getHttpServer(): any;
close(): any;
}

View File

@@ -28,3 +28,6 @@ export * from './http/http-server-factory.interface';
export * from './features/arguments-host.interface';
export * from './nest-express-application.interface';
export * from './nest-fastify-application.interface';
export * from './modules/provider.interface';
export * from './type.interface';
export * from './modules/forward-reference.interface';

View File

@@ -1,6 +1,6 @@
import { Transport } from '../../enums/transport.enum';
import { CustomTransportStrategy } from './custom-transport-strategy.interface';
import { MqttClientOptions } from '../external/mqtt-options.interface';
import { CustomTransportStrategy } from './custom-transport-strategy.interface';
export declare type MicroserviceOptions = GrpcOptions | TcpOptions | RedisOptions | NatsOptions | MqttOptions | CustomStrategy;
export interface CustomStrategy {
strategy?: CustomTransportStrategy;
@@ -12,6 +12,7 @@ export interface GrpcOptions {
url?: string;
credentials?: any;
protoPath: string;
root?: string;
package: string;
};
}

View File

@@ -1,19 +1,28 @@
import { MiddlewareConsumer } from './middleware-consumer.interface';
import { Type } from '../type.interface';
import { RouteInfo } from './middleware-configuration.interface';
import { MiddlewareConsumer } from './middleware-consumer.interface';
export interface MiddlewareConfigProxy {
/**
* Passes custom arguments to `resolve()` method of the middleware.
* Delegates custom arguments to the `resolve()` method of the middleware.
*
* @param {} ...data
* @returns {MiddlewareConfigProxy}
*/
with(...data: any[]): MiddlewareConfigProxy;
/**
* Attaches passed either routes (strings) or controllers to the processed middleware(s).
* When you pass Controller class Nest will attach middleware to every path defined within this controller.
* Excludes routes from the currently processed middleware.
* This excluded route has to use an exact same route path.
*
* @param {} ...routes
* @returns {MiddlewareConfigProxy}
*/
exclude(...routes: (string | RouteInfo)[]): MiddlewareConfigProxy;
/**
* Attaches passed either routes or controllers to the currently configured middleware.
* If you pass a class, Nest would attach middleware to every path defined within this controller.
*
* @param {} ...routes
* @returns {MiddlewareConsumer}
*/
forRoutes(...routes: (string | Type<any>)[]): MiddlewareConsumer;
forRoutes(...routes: (string | Type<any> | RouteInfo)[]): MiddlewareConsumer;
}

View File

@@ -1,5 +1,10 @@
import { RequestMethod } from '../../enums';
import { Type } from '../type.interface';
export interface MiddlewareConfiguration {
middleware: any;
forRoutes: (Type<any> | string)[];
export interface RouteInfo {
path: string;
method: RequestMethod;
}
export interface MiddlewareConfiguration<T = any> {
middleware: T;
forRoutes: (Type<any> | string | RouteInfo)[];
}

View File

@@ -1,11 +1,12 @@
import { Type } from '../type.interface';
import { MiddlewareConfigProxy } from './middleware-config-proxy.interface';
export interface MiddlewareConsumer {
/**
* Takes single middleware class or array of classes
* that subsequently could be attached to the passed either routes or controllers.
* Takes either middleware class/function or array of classes/functions
* that subsequently shall be attached to the passed routes.
*
* @param {any|any[]} middleware
* @returns {MiddlewareConfigProxy}
*/
apply(middleware: any | any[]): MiddlewareConfigProxy;
apply(...middleware: (Type<any> | Function)[]): MiddlewareConfigProxy;
}

View File

@@ -1 +1 @@
export declare type MiddlewareFunction = (req?, res?, next?) => any;
export declare type MiddlewareFunction<TRequest = any, TResponse = any, TResult = any> = (req?: TRequest, res?: TResponse, next?: Function) => TResult;

View File

@@ -0,0 +1,3 @@
export interface ForwardReference<T = any> {
forwardRef: T;
}

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -2,3 +2,5 @@ export * from './module-metadata.interface';
export * from './nest-module.interface';
export * from './on-init.interface';
export * from './dynamic-module.interface';
export * from './provider.interface';
export * from './forward-reference.interface';

View File

@@ -1,13 +1,14 @@
import { DynamicModule } from './dynamic-module.interface';
import { Type } from '../type.interface';
import { DynamicModule } from './dynamic-module.interface';
import { ForwardReference } from './forward-reference.interface';
import { Provider } from './provider.interface';
export interface ModuleMetadata {
imports?: Array<Type<any> | DynamicModule | any[]>;
imports?: Array<Type<any> | DynamicModule | Promise<DynamicModule> | ForwardReference>;
controllers?: Type<any>[];
providers?: Provider[];
exports?: Array<DynamicModule | string | Provider | any[]>;
exports?: Array<DynamicModule | Promise<DynamicModule> | string | Provider | ForwardReference>;
/** @deprecated */
modules?: Array<Type<any> | DynamicModule | any[]>;
modules?: Array<Type<any> | DynamicModule | Promise<DynamicModule> | ForwardReference>;
/** @deprecated */
components?: Provider[];
}

View File

@@ -3,9 +3,9 @@ export interface WebSocketAdapter<T = any> {
create(port: number, options?: T): any;
bindClientConnect(server: any, callback: (...args) => void): any;
bindClientDisconnect?(client: any, callback: (...args) => void): any;
bindMessageHandlers(client: any, handler: {
bindMessageHandlers(client: any, handlers: Array<{
message: any;
callback: (...args) => Observable<any> | Promise<any> | any;
}[], process: (data) => Observable<any>): any;
callback: (...args: any[]) => Observable<any> | Promise<any> | any;
}>, transform: (data: any) => Observable<any>): any;
close(server: any): any;
}

View File

@@ -1,6 +1,6 @@
{
"name": "@nestjs/common",
"version": "5.0.0-rc.2",
"version": "5.1.0",
"description": "Nest - modern, fast, powerful node.js web framework (@common)",
"author": "Kamil Mysliwiec",
"license": "MIT",

View File

@@ -5,28 +5,18 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const bad_request_exception_1 = require("../exceptions/bad-request.exception");
const index_1 = require("../index");
let ParseIntPipe = class ParseIntPipe {
transform(value, metadata) {
return __awaiter(this, void 0, void 0, function* () {
const isNumeric = 'string' === typeof value &&
!isNaN(parseFloat(value)) &&
isFinite(value);
if (!isNumeric) {
throw new bad_request_exception_1.BadRequestException('Validation failed (numeric string is expected)');
}
return parseInt(value, 10);
});
async transform(value, metadata) {
const isNumeric = 'string' === typeof value &&
!isNaN(parseFloat(value)) &&
isFinite(value);
if (!isNumeric) {
throw new bad_request_exception_1.BadRequestException('Validation failed (numeric string is expected)');
}
return parseInt(value, 10);
}
};
ParseIntPipe = __decorate([

View File

@@ -1,13 +1,16 @@
import { PipeTransform } from '../interfaces/features/pipe-transform.interface';
import { ArgumentMetadata } from '../index';
import { ValidatorOptions } from '../interfaces/external/validator-options.interface';
import { PipeTransform } from '../interfaces/features/pipe-transform.interface';
export interface ValidationPipeOptions extends ValidatorOptions {
transform?: boolean;
disableErrorMessages?: boolean;
}
export declare class ValidationPipe implements PipeTransform<any> {
private isTransformEnabled;
private validatorOptions;
protected isTransformEnabled: boolean;
protected isDetailedOutputDisabled: boolean;
protected validatorOptions: ValidatorOptions;
constructor(options?: ValidationPipeOptions);
transform(value: any, metadata: ArgumentMetadata): Promise<any>;
private toValidate(metadata);
toEmptyIfNil<T = any, R = any>(value: T): R | {};
}

View File

@@ -8,14 +8,6 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
@@ -27,38 +19,37 @@ var __rest = (this && this.__rest) || function (s, e) {
};
Object.defineProperty(exports, "__esModule", { value: true });
const index_1 = require("../index");
const load_package_util_1 = require("../utils/load-package.util");
const shared_utils_1 = require("../utils/shared.utils");
const component_decorator_1 = require("./../decorators/core/component.decorator");
const load_package_util_1 = require("../utils/load-package.util");
let classValidator = {};
let classTransformer = {};
let ValidationPipe = class ValidationPipe {
constructor(options) {
options = options || {};
const { transform } = options, validatorOptions = __rest(options, ["transform"]);
const { transform, disableErrorMessages } = options, validatorOptions = __rest(options, ["transform", "disableErrorMessages"]);
this.isTransformEnabled = !!transform;
this.validatorOptions = validatorOptions;
this.isDetailedOutputDisabled = disableErrorMessages;
const loadPkg = pkg => load_package_util_1.loadPackage(pkg, 'ValidationPipe');
classValidator = loadPkg('class-validator');
classTransformer = loadPkg('class-transformer');
}
transform(value, metadata) {
return __awaiter(this, void 0, void 0, function* () {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metadata)) {
return value;
}
const entity = classTransformer.plainToClass(metatype, value);
const errors = yield classValidator.validate(entity, this.validatorOptions);
if (errors.length > 0) {
throw new index_1.BadRequestException(errors);
}
return this.isTransformEnabled
? entity
: Object.keys(this.validatorOptions).length > 0
? classTransformer.classToPlain(entity)
: value;
});
async transform(value, metadata) {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metadata)) {
return value;
}
const entity = classTransformer.plainToClass(metatype, this.toEmptyIfNil(value));
const errors = await classValidator.validate(entity, this.validatorOptions);
if (errors.length > 0) {
throw new index_1.BadRequestException(this.isDetailedOutputDisabled ? undefined : errors);
}
return this.isTransformEnabled
? entity
: Object.keys(this.validatorOptions).length > 0
? classTransformer.classToPlain(entity)
: value;
}
toValidate(metadata) {
const { metatype, type } = metadata;
@@ -68,6 +59,9 @@ let ValidationPipe = class ValidationPipe {
const types = [String, Boolean, Number, Array, Object];
return !types.find(t => metatype === t) && !shared_utils_1.isNil(metatype);
}
toEmptyIfNil(value) {
return shared_utils_1.isNil(value) ? {} : value;
}
};
ValidationPipe = __decorate([
component_decorator_1.Injectable(),

View File

@@ -1,3 +1,2 @@
export declare const forwardRef: (fn: () => any) => {
forwardRef: () => any;
};
import { ForwardReference } from '../interfaces/modules/forward-reference.interface';
export declare const forwardRef: (fn: () => any) => ForwardReference<any>;

View File

@@ -1,3 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.forwardRef = (fn) => ({ forwardRef: fn });
exports.forwardRef = (fn) => ({
forwardRef: fn,
});

View File

@@ -14,7 +14,7 @@
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://api.travis-ci.org/nestjs/nest.svg?branch=master" alt="Travis" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://img.shields.io/travis/nestjs/nest/master.svg?label=linux" alt="Linux" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#6" alt="Coverage" /></a>
<a href="https://gitter.im/nestjs/nestjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=body_badge"><img src="https://badges.gitter.im/nestjs/nestjs.svg" alt="Gitter" /></a>
<a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
@@ -37,7 +37,8 @@
## Getting started
To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books:
* To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books:
* 要查看中文 [指南](readme_zh.md), 请访问 [docs.nestjs.cn](https://docs.nestjs.cn). :books:
## Support
@@ -47,56 +48,17 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="300" /></a>
#### Silver Sponsors
<a href="https://neoteric.eu/"><img src="https://nestjs.com/img/neoteric-cut.png" width="130" /></a> &nbsp; <a href="https://www.swingdev.io"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="160" /></a>
#### Sponsors
<a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.svg" width="150" /></a> &nbsp; <a href="https://www.swingdev.io"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="150" /></a>
<a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.svg" width="120" /></a> &nbsp; <a href="http://angularity.io"><img src="http://angularity.io/media/logo.svg" height="32" /></a> &nbsp; <a href="http://gojob.com"><img src="https://gojob.com/w/wp-content/uploads/2017/02/cropped-Logo-web-home.png" height="44" /> &nbsp; <a href="https://keycdn.com"><img src="https://nestjs.com/img/keycdn.svg" height="37" /></a> &nbsp; <a href="https://hostpresto.com"><img src="https://nestjs.com/img/hostpresto.png" height="32" /></a>
## Backers
<a href="https://opencollective.com/nest/backer/0/website" target="_blank"><img src="https://opencollective.com/nest/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/1/website" target="_blank"><img src="https://opencollective.com/nest/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/2/website" target="_blank"><img src="https://opencollective.com/nest/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/3/website" target="_blank"><img src="https://opencollective.com/nest/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/4/website" target="_blank"><img src="https://opencollective.com/nest/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/5/website" target="_blank"><img src="https://opencollective.com/nest/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/6/website" target="_blank"><img src="https://opencollective.com/nest/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/7/website" target="_blank"><img src="https://opencollective.com/nest/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/8/website" target="_blank"><img src="https://opencollective.com/nest/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/9/website" target="_blank"><img src="https://opencollective.com/nest/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/10/website" target="_blank"><img src="https://opencollective.com/nest/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/11/website" target="_blank"><img src="https://opencollective.com/nest/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/12/website" target="_blank"><img src="https://opencollective.com/nest/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/13/website" target="_blank"><img src="https://opencollective.com/nest/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/14/website" target="_blank"><img src="https://opencollective.com/nest/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/15/website" target="_blank"><img src="https://opencollective.com/nest/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/16/website" target="_blank"><img src="https://opencollective.com/nest/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/17/website" target="_blank"><img src="https://opencollective.com/nest/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/18/website" target="_blank"><img src="https://opencollective.com/nest/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/19/website" target="_blank"><img src="https://opencollective.com/nest/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/20/website" target="_blank"><img src="https://opencollective.com/nest/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/21/website" target="_blank"><img src="https://opencollective.com/nest/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/22/website" target="_blank"><img src="https://opencollective.com/nest/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/23/website" target="_blank"><img src="https://opencollective.com/nest/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/24/website" target="_blank"><img src="https://opencollective.com/nest/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/25/website" target="_blank"><img src="https://opencollective.com/nest/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/26/website" target="_blank"><img src="https://opencollective.com/nest/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/27/website" target="_blank"><img src="https://opencollective.com/nest/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/28/website" target="_blank"><img src="https://opencollective.com/nest/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/29/website" target="_blank"><img src="https://opencollective.com/nest/backer/29/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/30/website" target="_blank"><img src="https://opencollective.com/nest/backer/30/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/31/website" target="_blank"><img src="https://opencollective.com/nest/backer/31/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/32/website" target="_blank"><img src="https://opencollective.com/nest/backer/32/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/33/website" target="_blank"><img src="https://opencollective.com/nest/backer/33/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/34/website" target="_blank"><img src="https://opencollective.com/nest/backer/34/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/35/website" target="_blank"><img src="https://opencollective.com/nest/backer/35/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/36/website" target="_blank"><img src="https://opencollective.com/nest/backer/36/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/37/website" target="_blank"><img src="https://opencollective.com/nest/backer/37/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/38/website" target="_blank"><img src="https://opencollective.com/nest/backer/38/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/39/website" target="_blank"><img src="https://opencollective.com/nest/backer/39/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/40/website" target="_blank"><img src="https://opencollective.com/nest/backer/40/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/41/website" target="_blank"><img src="https://opencollective.com/nest/backer/41/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/42/website" target="_blank"><img src="https://opencollective.com/nest/backer/42/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/43/website" target="_blank"><img src="https://opencollective.com/nest/backer/43/avatar.svg"></a>
<a href="https://opencollective.com/nest"><img src="https://opencollective.com/nest/backers.svg?width=890"></a>
## Stay in touch
@@ -107,5 +69,3 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
## License
Nest is [MIT licensed](LICENSE).
<h4 align="center"> <a href="readme_zh.md">中文说明</a></h4>

View File

@@ -1,7 +1,9 @@
import { RequestMethod } from '@nestjs/common';
import { HttpServer, RequestHandler } from '@nestjs/common/interfaces';
import { ServeStaticOptions } from '@nestjs/common/interfaces/external/serve-static-options.interface';
export declare class ExpressAdapter implements HttpServer {
private readonly instance;
private readonly routerMethodFactory;
constructor(instance: any);
use(...args: any[]): any;
get(handler: RequestHandler): any;
@@ -26,6 +28,7 @@ export declare class ExpressAdapter implements HttpServer {
setNotFoundHandler(handler: Function): any;
setHeader(response: any, name: string, value: string): any;
getHttpServer(): any;
getInstance(): any;
close(): any;
set(...args: any[]): any;
enable(...args: any[]): any;
@@ -36,4 +39,5 @@ export declare class ExpressAdapter implements HttpServer {
setViewEngine(engine: string): any;
getRequestMethod(request: any): string;
getRequestUrl(request: any): string;
createMiddlewareFactory(requestMethod: RequestMethod): (path: string, callback: Function) => any;
}

View File

@@ -1,10 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express = require("express");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const express = require("express");
const router_method_factory_1 = require("../helpers/router-method-factory");
class ExpressAdapter {
constructor(instance) {
this.instance = instance;
this.routerMethodFactory = new router_method_factory_1.RouterMethodFactory();
}
use(...args) {
return this.instance.use(...args);
@@ -55,6 +57,9 @@ class ExpressAdapter {
getHttpServer() {
return this.instance;
}
getInstance() {
return this.instance;
}
close() {
return this.instance.close();
}
@@ -62,13 +67,13 @@ class ExpressAdapter {
return this.instance.set(...args);
}
enable(...args) {
return this.instance.set(...args);
return this.instance.enable(...args);
}
disable(...args) {
return this.instance.set(...args);
return this.instance.disable(...args);
}
engine(...args) {
return this.instance.set(...args);
return this.instance.engine(...args);
}
useStaticAssets(path, options) {
return this.use(express.static(path, options));
@@ -85,5 +90,10 @@ class ExpressAdapter {
getRequestUrl(request) {
return request.url;
}
createMiddlewareFactory(requestMethod) {
return this.routerMethodFactory
.get(this.instance, requestMethod)
.bind(this.instance);
}
}
exports.ExpressAdapter = ExpressAdapter;

View File

@@ -1,4 +1,5 @@
import { RequestHandler, ErrorHandler } from '@nestjs/common/interfaces';
import { RequestMethod } from '@nestjs/common';
import { ErrorHandler, RequestHandler } from '@nestjs/common/interfaces';
export declare class FastifyAdapter {
private readonly logger;
protected readonly instance: any;
@@ -26,6 +27,7 @@ export declare class FastifyAdapter {
setErrorHandler(handler: Function): any;
setNotFoundHandler(handler: Function): any;
getHttpServer(): any;
getInstance(): any;
register(...args: any[]): any;
inject(...args: any[]): any;
close(): any;
@@ -39,4 +41,5 @@ export declare class FastifyAdapter {
setHeader(response: any, name: string, value: string): any;
getRequestMethod(request: any): string;
getRequestUrl(request: any): string;
createMiddlewareFactory(requestMethod: RequestMethod): (path: string, callback: Function) => any;
}

View File

@@ -2,6 +2,7 @@
Object.defineProperty(exports, "__esModule", { value: true });
const common_1 = require("@nestjs/common");
const load_package_util_1 = require("@nestjs/common/utils/load-package.util");
const pathToRegexp = require("path-to-regexp");
class FastifyAdapter {
constructor(options) {
this.logger = new common_1.Logger(FastifyAdapter.name);
@@ -49,6 +50,9 @@ class FastifyAdapter {
getHttpServer() {
return this.instance.server;
}
getInstance() {
return this.instance;
}
register(...args) {
return this.instance.register(...args);
}
@@ -73,5 +77,20 @@ class FastifyAdapter {
getRequestUrl(request) {
return request.raw.url;
}
createMiddlewareFactory(requestMethod) {
return (path, callback) => {
const re = pathToRegexp(path);
this.instance.use(path, (req, res, next) => {
if (!re.exec(req.originalUrl + '/')) {
return next();
}
if (requestMethod === common_1.RequestMethod.ALL ||
req.method === common_1.RequestMethod[requestMethod]) {
return callback(req, res, next);
}
next();
});
};
}
}
exports.FastifyAdapter = FastifyAdapter;

View File

@@ -1,12 +1,4 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const exception_handler_1 = require("./exception-handler");
const messages_1 = require("./messages");
@@ -20,16 +12,14 @@ class ExceptionsZone {
throw messages_1.UNHANDLED_RUNTIME_EXCEPTION;
}
}
static asyncRun(fn) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield fn();
}
catch (e) {
this.exceptionHandler.handle(e);
throw messages_1.UNHANDLED_RUNTIME_EXCEPTION;
}
});
static async asyncRun(fn) {
try {
await fn();
}
catch (e) {
this.exceptionHandler.handle(e);
throw messages_1.UNHANDLED_RUNTIME_EXCEPTION;
}
}
}
ExceptionsZone.exceptionHandler = new exception_handler_1.ExceptionHandler();

View File

@@ -6,4 +6,4 @@ export declare const INVALID_MIDDLEWARE_CONFIGURATION = "Invalid middleware conf
export declare const UNKNOWN_REQUEST_MAPPING = "Request mapping properties not defined in the @RequestMapping() annotation!";
export declare const UNHANDLED_RUNTIME_EXCEPTION = "Unhandled Runtime Exception.";
export declare const INVALID_EXCEPTION_FILTER = "Invalid exception filters (@UseFilters()).";
export declare const MICROSERVICES_PACKAGE_NOT_FOUND_EXCEPTION = "Unable to load @nestjs/microservices package (please, make sure whether it's installed already).";
export declare const MICROSERVICES_PACKAGE_NOT_FOUND_EXCEPTION = "Unable to load @nestjs/microservices package. (Please make sure that it's already installed.)";

View File

@@ -1,19 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnknownDependenciesMessage = (type, index, length) => {
// Try to get the class name
// otherwise the string value
// if not known use +
const getDependencyName = arg => (arg && arg.name) || arg || '+';
exports.UnknownDependenciesMessage = (type, index, args) => {
let message = `Nest can't resolve dependencies of the ${type}`;
message += ` (`;
const args = new Array(length).fill('+');
args[index] = '?';
message += args.join(', ');
message += `). Please verify whether [${index}] argument is available in the current context.`;
message += `). Please make sure that the argument at index [${index}] is available in the current context.`;
return message;
};
exports.InvalidMiddlewareMessage = (name) => `The middleware doesn't provide the 'resolve' method (${name})`;
exports.InvalidModuleMessage = (scope) => `Nest cannot create the module instance. The frequent reason of this exception is the circular dependency between modules. Use forwardRef() to avoid it (read more https://docs.nestjs.com/advanced/circular-dependency). Scope [${scope}]`;
exports.UnknownExportMessage = (module) => `Nest cannot export component / module that is not a part of the currently proccessed module (${module}). Please verify whether each exported unit is available in this particular context.`;
exports.InvalidModuleMessage = (scope) => `Nest cannot create the module instance. Often, this is because of a circular dependency between modules. Use forwardRef() to avoid it. (Read more https://docs.nestjs.com/advanced/circular-dependency.) Scope [${scope}]`;
exports.UnknownExportMessage = (module) => `Nest cannot export a component/module that is not a part of the currently processed module (${module}). Please verify whether each exported unit is available in this particular context.`;
exports.INVALID_MIDDLEWARE_CONFIGURATION = `Invalid middleware configuration passed inside the module 'configure()' method.`;
exports.UNKNOWN_REQUEST_MAPPING = `Request mapping properties not defined in the @RequestMapping() annotation!`;
exports.UNHANDLED_RUNTIME_EXCEPTION = `Unhandled Runtime Exception.`;
exports.INVALID_EXCEPTION_FILTER = `Invalid exception filters (@UseFilters()).`;
exports.MICROSERVICES_PACKAGE_NOT_FOUND_EXCEPTION = `Unable to load @nestjs/microservices package (please, make sure whether it's installed already).`;
exports.MICROSERVICES_PACKAGE_NOT_FOUND_EXCEPTION = `Unable to load @nestjs/microservices package. (Please make sure that it's already installed.)`;

View File

@@ -1,8 +1,8 @@
import 'reflect-metadata';
import { Type } from '@nestjs/common/interfaces/index';
import { ExceptionFilter } from '@nestjs/common/interfaces/exceptions/exception-filter.interface';
import { ContextCreator } from './../helpers/context-creator';
import { Type } from '@nestjs/common/interfaces/index';
import 'reflect-metadata';
import { NestContainer } from '../injector/container';
import { ContextCreator } from './../helpers/context-creator';
export declare class BaseExceptionFilterContext extends ContextCreator {
private readonly container;
protected moduleContext: string;

View File

@@ -1,9 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
const iterare_1 = require("iterare");
const constants_1 = require("@nestjs/common/constants");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const iterare_1 = require("iterare");
require("reflect-metadata");
const context_creator_1 = require("./../helpers/context-creator");
class BaseExceptionFilterContext extends context_creator_1.ContextCreator {
constructor(container) {
@@ -24,7 +24,7 @@ class BaseExceptionFilterContext extends context_creator_1.ContextCreator {
.toArray();
}
getFilterInstance(filter) {
const isObject = !!filter.catch;
const isObject = filter.catch;
if (isObject) {
return filter;
}

View File

@@ -1,6 +1,5 @@
import { HttpServer } from '@nestjs/common';
import { HttpException, HttpServer } from '@nestjs/common';
import { ExceptionFilterMetadata } from '@nestjs/common/interfaces/exceptions/exception-filter-metadata.interface';
import { HttpException } from '@nestjs/common';
import { ArgumentsHost } from '@nestjs/common/interfaces/features/arguments-host.interface';
export declare class ExceptionsHandler {
private readonly applicationRef;

View File

@@ -1,10 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("../constants");
const common_1 = require("@nestjs/common");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const constants_1 = require("../constants");
const invalid_exception_filter_exception_1 = require("../errors/exceptions/invalid-exception-filter.exception");
const common_2 = require("@nestjs/common");
class ExceptionsHandler {
constructor(applicationRef) {
this.applicationRef = applicationRef;
@@ -13,13 +12,12 @@ class ExceptionsHandler {
next(exception, ctx) {
if (this.invokeCustomFilters(exception, ctx))
return;
if (!(exception instanceof common_2.HttpException)) {
if (!(exception instanceof common_1.HttpException)) {
const body = {
statusCode: 500,
message: constants_1.messages.UNKNOWN_EXCEPTION_MESSAGE,
};
const statusCode = 500;
this.applicationRef.reply(ctx.getArgByIndex(1), body, statusCode);
this.applicationRef.reply(ctx.getArgByIndex(1), body, body.statusCode);
if (this.isExceptionObject(exception)) {
return ExceptionsHandler.logger.error(exception.message, exception.stack);
}

View File

@@ -1,46 +1,34 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const rxjs_1 = require("rxjs");
const execution_context_host_1 = require("../helpers/execution-context.host");
class GuardsConsumer {
tryActivate(guards, args, instance, callback) {
return __awaiter(this, void 0, void 0, function* () {
if (!guards || shared_utils_1.isEmpty(guards)) {
return true;
}
const context = this.createContext(args, instance, callback);
for (const guard of guards) {
const result = guard.canActivate(context);
if (yield this.pickResult(result)) {
continue;
}
return false;
}
async tryActivate(guards, args, instance, callback) {
if (!guards || shared_utils_1.isEmpty(guards)) {
return true;
});
}
const context = this.createContext(args, instance, callback);
for (const guard of guards) {
const result = guard.canActivate(context);
if (await this.pickResult(result)) {
continue;
}
return false;
}
return true;
}
createContext(args, instance, callback) {
return new execution_context_host_1.ExecutionContextHost(args, instance.constructor, callback);
}
pickResult(result) {
return __awaiter(this, void 0, void 0, function* () {
if (result instanceof rxjs_1.Observable) {
return yield result.toPromise();
}
if (result instanceof Promise) {
return yield result;
}
return result;
});
async pickResult(result) {
if (result instanceof rxjs_1.Observable) {
return await result.toPromise();
}
if (result instanceof Promise) {
return await result;
}
return result;
}
}
exports.GuardsConsumer = GuardsConsumer;

View File

@@ -1,12 +1,4 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
const constants_1 = require("../guards/constants");
@@ -23,14 +15,14 @@ class ExternalContextCreator {
const module = this.findContextModuleName(instance.constructor);
const guards = this.guardsContextCreator.create(instance, callback, module);
const interceptors = this.interceptorsContextCreator.create(instance, callback, module);
return (...args) => __awaiter(this, void 0, void 0, function* () {
const canActivate = yield this.guardsConsumer.tryActivate(guards, args, instance, callback);
return async (...args) => {
const canActivate = await this.guardsConsumer.tryActivate(guards, args, instance, callback);
if (!canActivate) {
throw new common_1.HttpException(constants_1.FORBIDDEN_MESSAGE, common_1.HttpStatus.FORBIDDEN);
throw new common_1.ForbiddenException(constants_1.FORBIDDEN_MESSAGE);
}
const handler = () => callback.apply(instance, args);
return yield this.interceptorsConsumer.intercept(interceptors, args, instance, callback, handler);
});
return await this.interceptorsConsumer.intercept(interceptors, args, instance, callback, handler);
};
}
findContextModuleName(constructor) {
const className = constructor.name;

View File

@@ -1,7 +1,9 @@
export { MiddlewareBuilder } from './middleware/builder';
export { ModuleRef } from './injector/module-ref';
export { NestFactory } from './nest-factory';
export { HTTP_SERVER_REF } from './injector/tokens';
export { APP_INTERCEPTOR, APP_FILTER, APP_GUARD, APP_PIPE } from './constants';
export * from './adapters';
export * from './services';
export * from './nest-application';
export * from './nest-application-context';

View File

@@ -15,11 +15,14 @@ var module_ref_1 = require("./injector/module-ref");
exports.ModuleRef = module_ref_1.ModuleRef;
var nest_factory_1 = require("./nest-factory");
exports.NestFactory = nest_factory_1.NestFactory;
var tokens_1 = require("./injector/tokens");
exports.HTTP_SERVER_REF = tokens_1.HTTP_SERVER_REF;
var constants_1 = require("./constants");
exports.APP_INTERCEPTOR = constants_1.APP_INTERCEPTOR;
exports.APP_FILTER = constants_1.APP_FILTER;
exports.APP_GUARD = constants_1.APP_GUARD;
exports.APP_PIPE = constants_1.APP_PIPE;
__export(require("./adapters"));
__export(require("./services"));
__export(require("./nest-application"));
__export(require("./nest-application-context"));

View File

@@ -1,4 +1,4 @@
import { Type, DynamicModule } from '@nestjs/common/interfaces';
import { DynamicModule, Type } from '@nestjs/common/interfaces';
export interface ModuleFactory {
type: Type<any>;
token: string;
@@ -6,10 +6,11 @@ export interface ModuleFactory {
}
export declare class ModuleCompiler {
private readonly moduleTokenFactory;
compile(metatype: Type<any> | DynamicModule, scope: Type<any>[]): ModuleFactory;
extractMetadata(metatype: Type<any> | DynamicModule): {
compile(metatype: Type<any> | DynamicModule | Promise<DynamicModule>, scope: Type<any>[]): Promise<ModuleFactory>;
extractMetadata(metatype: Type<any> | DynamicModule | Promise<DynamicModule>): Promise<{
type: Type<any>;
dynamicMetadata?: Partial<DynamicModule> | undefined;
};
}>;
isDynamicModule(module: Type<any> | DynamicModule): module is DynamicModule;
isDefferedModule(module: Type<any> | DynamicModule | Promise<DynamicModule>): module is Promise<DynamicModule>;
}

View File

@@ -14,12 +14,13 @@ class ModuleCompiler {
constructor() {
this.moduleTokenFactory = new module_token_factory_1.ModuleTokenFactory();
}
compile(metatype, scope) {
const { type, dynamicMetadata } = this.extractMetadata(metatype);
async compile(metatype, scope) {
const { type, dynamicMetadata } = await this.extractMetadata(metatype);
const token = this.moduleTokenFactory.create(type, scope, dynamicMetadata);
return { type, dynamicMetadata, token };
}
extractMetadata(metatype) {
async extractMetadata(metatype) {
metatype = this.isDefferedModule(metatype) ? await metatype : metatype;
if (!this.isDynamicModule(metatype)) {
return { type: metatype };
}
@@ -29,5 +30,8 @@ class ModuleCompiler {
isDynamicModule(module) {
return !!module.module;
}
isDefferedModule(module) {
return module && module instanceof Promise;
}
}
exports.ModuleCompiler = ModuleCompiler;

View File

@@ -1,9 +1,9 @@
import 'reflect-metadata';
import { Type } from '@nestjs/common/interfaces/type.interface';
import { Module } from './module';
import { DynamicModule } from '@nestjs/common';
import { ModulesContainer } from './modules-container';
import { Type } from '@nestjs/common/interfaces/type.interface';
import 'reflect-metadata';
import { ApplicationConfig } from './../application-config';
import { Module } from './module';
import { ModulesContainer } from './modules-container';
export declare class NestContainer {
private readonly _applicationConfig;
private readonly globalModules;
@@ -15,13 +15,13 @@ export declare class NestContainer {
readonly applicationConfig: ApplicationConfig | undefined;
setApplicationRef(applicationRef: any): void;
getApplicationRef(): any;
addModule(metatype: Type<any> | DynamicModule, scope: Type<any>[]): void;
addModule(metatype: Type<any> | DynamicModule | Promise<DynamicModule>, scope: Type<any>[]): Promise<void>;
addDynamicMetadata(token: string, dynamicModuleMetadata: Partial<DynamicModule>, scope: Type<any>[]): any;
addDynamicModules(modules: any[], scope: Type<any>[]): any;
isGlobalModule(metatype: Type<any>): boolean;
addGlobalModule(module: Module): void;
getModules(): ModulesContainer;
addRelatedModule(relatedModule: Type<any> | DynamicModule, token: string): void;
addRelatedModule(relatedModule: Type<any> | DynamicModule, token: string): Promise<void>;
addComponent(component: Type<any>, token: string): string;
addInjectable(injectable: Type<any>, token: string): void;
addExportedComponent(exportedComponent: Type<any>, token: string): void;

View File

@@ -1,12 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
const constants_1 = require("@nestjs/common/constants");
const module_1 = require("./module");
require("reflect-metadata");
const unknown_module_exception_1 = require("../errors/exceptions/unknown-module.exception");
const invalid_module_exception_1 = require("./../errors/exceptions/invalid-module.exception");
const modules_container_1 = require("./modules-container");
const compiler_1 = require("./compiler");
const module_1 = require("./module");
const modules_container_1 = require("./modules-container");
class NestContainer {
constructor(_applicationConfig = void 0) {
this._applicationConfig = _applicationConfig;
@@ -24,11 +24,11 @@ class NestContainer {
getApplicationRef() {
return this.applicationRef;
}
addModule(metatype, scope) {
async addModule(metatype, scope) {
if (!metatype) {
throw new invalid_module_exception_1.InvalidModuleException(scope);
}
const { type, dynamicMetadata, token } = this.moduleCompiler.compile(metatype, scope);
const { type, dynamicMetadata, token } = await this.moduleCompiler.compile(metatype, scope);
if (this.modules.has(token)) {
return;
}
@@ -61,13 +61,13 @@ class NestContainer {
getModules() {
return this.modules;
}
addRelatedModule(relatedModule, token) {
async addRelatedModule(relatedModule, token) {
if (!this.modules.has(token))
return;
const module = this.modules.get(token);
const parent = module.metatype;
const scope = [].concat(module.scope, parent);
const { type, dynamicMetadata, token: relatedModuleToken, } = this.moduleCompiler.compile(relatedModule, scope);
const { token: relatedModuleToken } = await this.moduleCompiler.compile(relatedModule, scope);
const related = this.modules.get(relatedModuleToken);
module.addRelatedModule(related);
}

View File

@@ -1,10 +1,10 @@
import 'reflect-metadata';
import { InstanceWrapper } from './container';
import { Module } from './module';
import { Type } from '@nestjs/common/interfaces/type.interface';
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import { Injectable } from '@nestjs/common/interfaces/injectable.interface';
import { Type } from '@nestjs/common/interfaces/type.interface';
import 'reflect-metadata';
import { MiddlewareWrapper } from '../middleware/container';
import { InstanceWrapper } from './container';
import { Module } from './module';
export declare class Injector {
loadInstanceOfMiddleware(wrapper: MiddlewareWrapper, collection: Map<string, MiddlewareWrapper>, module: Module): Promise<void>;
loadInstanceOfRoute(wrapper: InstanceWrapper<Controller>, module: Module): Promise<void>;
@@ -25,18 +25,16 @@ export declare class Injector {
index: number;
length: number;
}, wrapper: InstanceWrapper<T>): Promise<any>;
lookupComponent(components: Map<string, any>, module: Module, {name, index, length}: {
lookupComponent<T = any>(components: Map<string, any>, module: Module, {name, index, length}: {
name: any;
index: number;
length: number;
}, {metatype}: {
metatype: any;
}): Promise<any>;
lookupComponentInExports(components: Map<string, any>, {name, index, length}: {
}, wrapper: InstanceWrapper<T>): Promise<any>;
lookupComponentInExports<T = any>(components: Map<string, any>, {name, index, length}: {
name: any;
index: number;
length: number;
}, module: Module, metatype: any): Promise<any>;
}, module: Module, wrapper: InstanceWrapper<T>): Promise<any>;
lookupComponentInRelatedModules(module: Module, name: any): Promise<any>;
resolveFactoryInstance(factoryResult: any): Promise<any>;
flatMap(modules: Module[]): Module[];

View File

@@ -1,45 +1,31 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
const unknown_dependencies_exception_1 = require("../errors/exceptions/unknown-dependencies.exception");
const runtime_exception_1 = require("../errors/exceptions/runtime.exception");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const constants_1 = require("@nestjs/common/constants");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
require("reflect-metadata");
const runtime_exception_1 = require("../errors/exceptions/runtime.exception");
const unknown_dependencies_exception_1 = require("../errors/exceptions/unknown-dependencies.exception");
const undefined_dependency_exception_1 = require("./../errors/exceptions/undefined-dependency.exception");
class Injector {
loadInstanceOfMiddleware(wrapper, collection, module) {
return __awaiter(this, void 0, void 0, function* () {
const { metatype } = wrapper;
const currentMetatype = collection.get(metatype.name);
if (currentMetatype.instance !== null)
return;
yield this.resolveConstructorParams(wrapper, module, null, instances => {
collection.set(metatype.name, {
instance: new metatype(...instances),
metatype,
});
async loadInstanceOfMiddleware(wrapper, collection, module) {
const { metatype } = wrapper;
const currentMetatype = collection.get(metatype.name);
if (currentMetatype.instance !== null)
return;
await this.resolveConstructorParams(wrapper, module, null, instances => {
collection.set(metatype.name, {
instance: new metatype(...instances),
metatype,
});
});
}
loadInstanceOfRoute(wrapper, module) {
return __awaiter(this, void 0, void 0, function* () {
const routes = module.routes;
yield this.loadInstance(wrapper, routes, module);
});
async loadInstanceOfRoute(wrapper, module) {
const routes = module.routes;
await this.loadInstance(wrapper, routes, module);
}
loadInstanceOfInjectable(wrapper, module) {
return __awaiter(this, void 0, void 0, function* () {
const injectables = module.injectables;
yield this.loadInstance(wrapper, injectables, module);
});
async loadInstanceOfInjectable(wrapper, module) {
const injectables = module.injectables;
await this.loadInstance(wrapper, injectables, module);
}
loadPrototypeOfInstance({ metatype, name }, collection) {
if (!collection)
@@ -49,11 +35,9 @@ class Injector {
return null;
collection.set(name, Object.assign({}, collection.get(name), { instance: Object.create(metatype.prototype) }));
}
loadInstanceOfComponent(wrapper, module) {
return __awaiter(this, void 0, void 0, function* () {
const components = module.components;
yield this.loadInstance(wrapper, components, module);
});
async loadInstanceOfComponent(wrapper, module) {
const components = module.components;
await this.loadInstance(wrapper, components, module);
}
applyDoneSubject(wrapper) {
let done;
@@ -63,47 +47,43 @@ class Injector {
wrapper.isPending = true;
return done;
}
loadInstance(wrapper, collection, module) {
return __awaiter(this, void 0, void 0, function* () {
if (wrapper.isPending) {
return yield wrapper.done$;
async loadInstance(wrapper, collection, module) {
if (wrapper.isPending) {
return await wrapper.done$;
}
const done = this.applyDoneSubject(wrapper);
const { metatype, name, inject } = wrapper;
const currentMetatype = collection.get(name);
if (shared_utils_1.isUndefined(currentMetatype)) {
throw new runtime_exception_1.RuntimeException();
}
if (currentMetatype.isResolved)
return null;
await this.resolveConstructorParams(wrapper, module, inject, async (instances) => {
if (shared_utils_1.isNil(inject)) {
currentMetatype.instance = Object.assign(currentMetatype.instance, new metatype(...instances));
}
const done = this.applyDoneSubject(wrapper);
const { metatype, name, inject } = wrapper;
const currentMetatype = collection.get(name);
if (shared_utils_1.isUndefined(currentMetatype)) {
throw new runtime_exception_1.RuntimeException();
else {
const factoryResult = currentMetatype.metatype(...instances);
currentMetatype.instance = await this.resolveFactoryInstance(factoryResult);
}
if (currentMetatype.isResolved)
return null;
yield this.resolveConstructorParams(wrapper, module, inject, (instances) => __awaiter(this, void 0, void 0, function* () {
if (shared_utils_1.isNil(inject)) {
currentMetatype.instance = Object.assign(currentMetatype.instance, new metatype(...instances));
}
else {
const factoryResult = currentMetatype.metatype(...instances);
currentMetatype.instance = yield this.resolveFactoryInstance(factoryResult);
}
currentMetatype.isResolved = true;
done();
}));
currentMetatype.isResolved = true;
done();
});
}
resolveConstructorParams(wrapper, module, inject, callback) {
return __awaiter(this, void 0, void 0, function* () {
let isResolved = true;
const args = shared_utils_1.isNil(inject)
? this.reflectConstructorParams(wrapper.metatype)
: inject;
const instances = yield Promise.all(args.map((param, index) => __awaiter(this, void 0, void 0, function* () {
const paramWrapper = yield this.resolveSingleParam(wrapper, param, { index, length: args.length }, module);
if (!paramWrapper.isResolved && !paramWrapper.forwardRef) {
isResolved = false;
}
return paramWrapper.instance;
})));
isResolved && (yield callback(instances));
});
async resolveConstructorParams(wrapper, module, inject, callback) {
let isResolved = true;
const args = shared_utils_1.isNil(inject)
? this.reflectConstructorParams(wrapper.metatype)
: inject;
const instances = await Promise.all(args.map(async (param, index) => {
const paramWrapper = await this.resolveSingleParam(wrapper, param, { index, length: args.length }, module);
if (!paramWrapper.isResolved && !paramWrapper.forwardRef) {
isResolved = false;
}
return paramWrapper.instance;
}));
isResolved && (await callback(instances));
}
reflectConstructorParams(type) {
const paramtypes = Reflect.getMetadata(constants_1.PARAMTYPES_METADATA, type) || [];
@@ -114,14 +94,12 @@ class Injector {
reflectSelfParams(type) {
return Reflect.getMetadata(constants_1.SELF_DECLARED_DEPS_METADATA, type) || [];
}
resolveSingleParam(wrapper, param, { index, length }, module) {
return __awaiter(this, void 0, void 0, function* () {
if (shared_utils_1.isUndefined(param)) {
throw new undefined_dependency_exception_1.UndefinedDependencyException(wrapper.name, index, length);
}
const token = this.resolveParamToken(wrapper, param);
return yield this.resolveComponentInstance(module, shared_utils_1.isFunction(token) ? token.name : token, { index, length }, wrapper);
});
async resolveSingleParam(wrapper, param, { index, length }, module) {
if (shared_utils_1.isUndefined(param)) {
throw new undefined_dependency_exception_1.UndefinedDependencyException(wrapper.name, index, length);
}
const token = this.resolveParamToken(wrapper, param);
return await this.resolveComponentInstance(module, shared_utils_1.isFunction(token) ? token.name : token, { index, length }, wrapper);
}
resolveParamToken(wrapper, param) {
if (!param.forwardRef) {
@@ -130,60 +108,50 @@ class Injector {
wrapper.forwardRef = true;
return param.forwardRef();
}
resolveComponentInstance(module, name, { index, length }, wrapper) {
return __awaiter(this, void 0, void 0, function* () {
const components = module.components;
const instanceWrapper = yield this.lookupComponent(components, module, { name, index, length }, wrapper);
if (!instanceWrapper.isResolved && !instanceWrapper.forwardRef) {
yield this.loadInstanceOfComponent(instanceWrapper, module);
}
if (instanceWrapper.async) {
instanceWrapper.instance = yield instanceWrapper.instance;
}
return instanceWrapper;
});
async resolveComponentInstance(module, name, { index, length }, wrapper) {
const components = module.components;
const instanceWrapper = await this.lookupComponent(components, module, { name, index, length }, wrapper);
if (!instanceWrapper.isResolved && !instanceWrapper.forwardRef) {
await this.loadInstanceOfComponent(instanceWrapper, module);
}
if (instanceWrapper.async) {
instanceWrapper.instance = await instanceWrapper.instance;
}
return instanceWrapper;
}
lookupComponent(components, module, { name, index, length }, { metatype }) {
return __awaiter(this, void 0, void 0, function* () {
const scanInExports = () => this.lookupComponentInExports(components, { name, index, length }, module, metatype);
return components.has(name) ? components.get(name) : yield scanInExports();
});
async lookupComponent(components, module, { name, index, length }, wrapper) {
const scanInExports = () => this.lookupComponentInExports(components, { name, index, length }, module, wrapper);
return components.has(name) ? components.get(name) : await scanInExports();
}
lookupComponentInExports(components, { name, index, length }, module, metatype) {
return __awaiter(this, void 0, void 0, function* () {
const instanceWrapper = yield this.lookupComponentInRelatedModules(module, name);
if (shared_utils_1.isNil(instanceWrapper)) {
throw new unknown_dependencies_exception_1.UnknownDependenciesException(metatype.name, index, length);
}
return instanceWrapper;
});
async lookupComponentInExports(components, { name, index, length }, module, wrapper) {
const instanceWrapper = await this.lookupComponentInRelatedModules(module, name);
if (shared_utils_1.isNil(instanceWrapper)) {
throw new unknown_dependencies_exception_1.UnknownDependenciesException(wrapper.name, index, length);
}
return instanceWrapper;
}
lookupComponentInRelatedModules(module, name) {
return __awaiter(this, void 0, void 0, function* () {
let component = null;
const relatedModules = module.relatedModules || [];
for (const relatedModule of this.flatMap([...relatedModules.values()])) {
const { components, exports } = relatedModule;
if (!exports.has(name) || !components.has(name)) {
continue;
}
component = components.get(name);
if (!component.isResolved && !component.forwardRef) {
yield this.loadInstanceOfComponent(component, relatedModule);
break;
}
async lookupComponentInRelatedModules(module, name) {
let component = null;
const relatedModules = module.relatedModules || [];
for (const relatedModule of this.flatMap([...relatedModules.values()])) {
const { components, exports } = relatedModule;
if (!exports.has(name) || !components.has(name)) {
continue;
}
return component;
});
component = components.get(name);
if (!component.isResolved && !component.forwardRef) {
await this.loadInstanceOfComponent(component, relatedModule);
break;
}
}
return component;
}
resolveFactoryInstance(factoryResult) {
return __awaiter(this, void 0, void 0, function* () {
if (!(factoryResult instanceof Promise)) {
return factoryResult;
}
const result = yield factoryResult;
return result;
});
async resolveFactoryInstance(factoryResult) {
if (!(factoryResult instanceof Promise)) {
return factoryResult;
}
const result = await factoryResult;
return result;
}
flatMap(modules) {
if (!modules) {
@@ -192,7 +160,7 @@ class Injector {
const flatten = (module) => {
const { relatedModules, exports } = module;
return this.flatMap([...relatedModules.values()]
.filter(related => !!related)
.filter(related => related)
.filter(related => {
const { metatype } = related;
return exports.has(metatype.name);

View File

@@ -1,28 +1,18 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const injector_1 = require("./injector");
const common_1 = require("@nestjs/common");
const messages_1 = require("../helpers/messages");
const injector_1 = require("./injector");
class InstanceLoader {
constructor(container) {
this.container = container;
this.injector = new injector_1.Injector();
this.logger = new common_1.Logger(InstanceLoader.name, true);
}
createInstancesOfDependencies() {
return __awaiter(this, void 0, void 0, function* () {
const modules = this.container.getModules();
this.createPrototypes(modules);
yield this.createInstances(modules);
});
async createInstancesOfDependencies() {
const modules = this.container.getModules();
this.createPrototypes(modules);
await this.createInstances(modules);
}
createPrototypes(modules) {
modules.forEach(module => {
@@ -31,46 +21,38 @@ class InstanceLoader {
this.createPrototypesOfRoutes(module);
});
}
createInstances(modules) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([...modules.values()].map((module) => __awaiter(this, void 0, void 0, function* () {
yield this.createInstancesOfComponents(module);
yield this.createInstancesOfInjectables(module);
yield this.createInstancesOfRoutes(module);
const { name } = module.metatype;
this.logger.log(messages_1.moduleInitMessage(name));
})));
});
async createInstances(modules) {
await Promise.all([...modules.values()].map(async (module) => {
await this.createInstancesOfComponents(module);
await this.createInstancesOfInjectables(module);
await this.createInstancesOfRoutes(module);
const { name } = module.metatype;
this.logger.log(messages_1.moduleInitMessage(name));
}));
}
createPrototypesOfComponents(module) {
module.components.forEach(wrapper => {
this.injector.loadPrototypeOfInstance(wrapper, module.components);
});
}
createInstancesOfComponents(module) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([...module.components.values()].map((wrapper) => __awaiter(this, void 0, void 0, function* () { return yield this.injector.loadInstanceOfComponent(wrapper, module); })));
});
async createInstancesOfComponents(module) {
await Promise.all([...module.components.values()].map(async (wrapper) => await this.injector.loadInstanceOfComponent(wrapper, module)));
}
createPrototypesOfRoutes(module) {
module.routes.forEach(wrapper => {
this.injector.loadPrototypeOfInstance(wrapper, module.routes);
});
}
createInstancesOfRoutes(module) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([...module.routes.values()].map((wrapper) => __awaiter(this, void 0, void 0, function* () { return yield this.injector.loadInstanceOfRoute(wrapper, module); })));
});
async createInstancesOfRoutes(module) {
await Promise.all([...module.routes.values()].map(async (wrapper) => await this.injector.loadInstanceOfRoute(wrapper, module)));
}
createPrototypesOfInjectables(module) {
module.injectables.forEach(wrapper => {
this.injector.loadPrototypeOfInstance(wrapper, module.injectables);
});
}
createInstancesOfInjectables(module) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([...module.injectables.values()].map((wrapper) => __awaiter(this, void 0, void 0, function* () { return yield this.injector.loadInstanceOfInjectable(wrapper, module); })));
});
async createInstancesOfInjectables(module) {
await Promise.all([...module.injectables.values()].map(async (wrapper) => await this.injector.loadInstanceOfInjectable(wrapper, module)));
}
}
exports.InstanceLoader = InstanceLoader;

View File

@@ -1,5 +1,5 @@
import { Type } from '@nestjs/common/interfaces/type.interface';
import { DynamicModule } from '@nestjs/common';
import { Type } from '@nestjs/common/interfaces/type.interface';
export declare class ModuleTokenFactory {
create(metatype: Type<any>, scope: Type<any>[], dynamicModuleMetadata?: Partial<DynamicModule> | undefined): string;
getDynamicMetadataToken(dynamicModuleMetadata: Partial<DynamicModule> | undefined): string;

View File

@@ -1,6 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("@nestjs/common/constants");
const hash = require("object-hash");
class ModuleTokenFactory {
create(metatype, scope, dynamicModuleMetadata) {
const reflectedScope = this.reflectScope(metatype);
@@ -10,7 +11,7 @@ class ModuleTokenFactory {
dynamic: this.getDynamicMetadataToken(dynamicModuleMetadata),
scope: isSingleScoped ? this.getScopeStack(scope) : reflectedScope,
};
return JSON.stringify(opaqueToken);
return hash(opaqueToken);
}
getDynamicMetadataToken(dynamicModuleMetadata) {
return dynamicModuleMetadata ? JSON.stringify(dynamicModuleMetadata) : '';

View File

@@ -1,6 +1,6 @@
import { InstanceWrapper, NestContainer } from './container';
import { Injectable, Controller, NestModule, DynamicModule } from '@nestjs/common/interfaces';
import { Controller, DynamicModule, Injectable, NestModule } from '@nestjs/common/interfaces';
import { Type } from '@nestjs/common/interfaces/type.interface';
import { InstanceWrapper, NestContainer } from './container';
export interface CustomComponent {
provide: any;
name: string;

View File

@@ -1,16 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const unknown_export_exception_1 = require("../errors/exceptions/unknown-export.exception");
const module_ref_1 = require("./module-ref");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const runtime_exception_1 = require("../errors/exceptions/runtime.exception");
const external_context_creator_1 = require("./../helpers/external-context-creator");
const guards_context_creator_1 = require("./../guards/guards-context-creator");
const interceptors_context_creator_1 = require("./../interceptors/interceptors-context-creator");
const interceptors_consumer_1 = require("./../interceptors/interceptors-consumer");
const guards_consumer_1 = require("./../guards/guards-consumer");
const modules_container_1 = require("./modules-container");
const unknown_export_exception_1 = require("../errors/exceptions/unknown-export.exception");
const reflector_service_1 = require("../services/reflector.service");
const guards_consumer_1 = require("./../guards/guards-consumer");
const guards_context_creator_1 = require("./../guards/guards-context-creator");
const external_context_creator_1 = require("./../helpers/external-context-creator");
const interceptors_consumer_1 = require("./../interceptors/interceptors-consumer");
const interceptors_context_creator_1 = require("./../interceptors/interceptors-context-creator");
const module_ref_1 = require("./module-ref");
const modules_container_1 = require("./modules-container");
const tokens_1 = require("./tokens");
class Module {
constructor(_metatype, _scope, container) {
@@ -217,7 +217,7 @@ class Module {
const relatedModules = [...this._relatedModules.values()];
const modulesTokens = relatedModules
.map(({ metatype }) => metatype)
.filter(metatype => !!metatype)
.filter(metatype => metatype)
.map(({ name }) => name);
if (modulesTokens.indexOf(token) < 0) {
const { name } = this.metatype;

View File

@@ -1,28 +1,18 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
const execution_context_host_1 = require("../helpers/execution-context.host");
class InterceptorsConsumer {
intercept(interceptors, args, instance, callback, next) {
return __awaiter(this, void 0, void 0, function* () {
if (!interceptors || shared_utils_1.isEmpty(interceptors)) {
return yield yield next();
}
const context = this.createContext(args, instance, callback);
const start$ = rxjs_1.defer(() => this.transformDeffered(next));
const result$ = yield interceptors.reduce((stream$, interceptor) => __awaiter(this, void 0, void 0, function* () { return yield interceptor.intercept(context, yield stream$); }), Promise.resolve(start$));
return yield result$.toPromise();
});
async intercept(interceptors, args, instance, callback, next) {
if (!interceptors || shared_utils_1.isEmpty(interceptors)) {
return await await next();
}
const context = this.createContext(args, instance, callback);
const start$ = rxjs_1.defer(() => this.transformDeffered(next));
const result$ = await interceptors.reduce(async (stream$, interceptor) => await interceptor.intercept(context, await stream$), Promise.resolve(start$));
return await result$.toPromise();
}
createContext(args, instance, callback) {
return new execution_context_host_1.ExecutionContextHost(args, instance.constructor, callback);

View File

@@ -1,14 +1,13 @@
import { MiddlewareConfiguration } from '@nestjs/common/interfaces/middleware/middleware-configuration.interface';
import { Type, MiddlewareConsumer } from '@nestjs/common/interfaces';
import { MiddlewareConsumer, Type } from '@nestjs/common/interfaces';
import { MiddlewareConfigProxy } from '@nestjs/common/interfaces/middleware';
import { MiddlewareConfiguration } from '@nestjs/common/interfaces/middleware/middleware-configuration.interface';
import { RoutesMapper } from './routes-mapper';
export declare class MiddlewareBuilder implements MiddlewareConsumer {
private readonly routesMapper;
private readonly middlewareCollection;
private readonly logger;
constructor(routesMapper: RoutesMapper);
apply(...middleware: Array<Type<any> | Function | any>): MiddlewareConfigProxy;
build(): MiddlewareConfiguration[];
build(): MiddlewareConfiguration<any>[];
private bindValuesToResolve(middleware, resolveParams);
private static ConfigProxy;
}

View File

@@ -1,15 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const bind_resolve_values_util_1 = require("@nestjs/common/utils/bind-resolve-values.util");
const logger_service_1 = require("@nestjs/common/services/logger.service");
const utils_1 = require("./utils");
const common_1 = require("@nestjs/common");
const dependencies_decorator_1 = require("@nestjs/common/decorators/core/dependencies.decorator");
const bind_resolve_values_util_1 = require("@nestjs/common/utils/bind-resolve-values.util");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const utils_1 = require("./utils");
class MiddlewareBuilder {
constructor(routesMapper) {
this.routesMapper = routesMapper;
this.middlewareCollection = new Set();
this.logger = new logger_service_1.Logger(MiddlewareBuilder.name);
}
apply(...middleware) {
return new MiddlewareBuilder.ConfigProxy(this, dependencies_decorator_1.flatten(middleware));
@@ -29,18 +28,27 @@ MiddlewareBuilder.ConfigProxy = class {
constructor(builder, middleware) {
this.builder = builder;
this.contextParameters = null;
this.excludedRoutes = [];
this.includedRoutes = utils_1.filterMiddleware(middleware);
}
getExcludedRoutes() {
return this.excludedRoutes;
}
with(...args) {
this.contextParameters = args;
return this;
}
exclude(...routes) {
const { routesMapper } = this.builder;
this.excludedRoutes = this.mapRoutesToFlatList(routes.map(route => routesMapper.mapRouteToRouteInfo(route)));
return this;
}
forRoutes(...routes) {
const { middlewareCollection, bindValuesToResolve, routesMapper, } = this.builder;
const forRoutes = this.mapRoutesToFlatList(routes.map(route => routesMapper.mapRouteToRouteProps(route)));
const forRoutes = this.mapRoutesToFlatList(routes.map(route => routesMapper.mapRouteToRouteInfo(route)));
const configuration = {
middleware: bindValuesToResolve(this.includedRoutes, this.contextParameters),
forRoutes,
forRoutes: forRoutes.filter(route => !this.isRouteExcluded(route)),
};
middlewareCollection.add(configuration);
return this.builder;
@@ -48,5 +56,19 @@ MiddlewareBuilder.ConfigProxy = class {
mapRoutesToFlatList(forRoutes) {
return forRoutes.reduce((a, b) => a.concat(b));
}
isRouteExcluded(routeInfo) {
const pathLastIndex = routeInfo.path.length - 1;
const validatedRoutePath = routeInfo.path[pathLastIndex] === '/'
? routeInfo.path.slice(0, pathLastIndex)
: routeInfo.path;
return this.excludedRoutes.some(excluded => {
const isPathEqual = validatedRoutePath === excluded.path;
if (!isPathEqual) {
return false;
}
return (routeInfo.method === excluded.method ||
excluded.method === common_1.RequestMethod.ALL);
});
}
};
exports.MiddlewareBuilder = MiddlewareBuilder;

View File

@@ -1,21 +1,21 @@
import { NestContainer } from '../injector/container';
import { MiddlewareContainer } from './container';
import { MiddlewareConfiguration, RouteInfo } from '@nestjs/common/interfaces/middleware/middleware-configuration.interface';
import { NestModule } from '@nestjs/common/interfaces/modules/nest-module.interface';
import { MiddlewareConfiguration } from '@nestjs/common/interfaces/middleware/middleware-configuration.interface';
import { Module } from '../injector/module';
import { ApplicationConfig } from '../application-config';
import { NestContainer } from '../injector/container';
import { Module } from '../injector/module';
import { MiddlewareContainer } from './container';
export declare class MiddlewareModule {
private readonly routerProxy;
private readonly routerMethodFactory;
private routerExceptionFilter;
private routesMapper;
private resolver;
private config;
register(middlewareContainer: MiddlewareContainer, container: NestContainer, config: ApplicationConfig): Promise<void>;
resolveMiddleware(middlewareContainer: MiddlewareContainer, modules: Map<string, Module>): Promise<void>;
loadConfiguration(middlewareContainer: MiddlewareContainer, instance: NestModule, module: string): void;
registerMiddleware(middlewareContainer: MiddlewareContainer, applicationRef: any): Promise<void>;
registerMiddlewareConfig(middlewareContainer: MiddlewareContainer, config: MiddlewareConfiguration, module: string, applicationRef: any): Promise<void>;
registerRouteMiddleware(middlewareContainer: MiddlewareContainer, routePath: string, config: MiddlewareConfiguration, module: string, applicationRef: any): Promise<void>;
registerRouteMiddleware(middlewareContainer: MiddlewareContainer, routeInfo: RouteInfo, config: MiddlewareConfiguration, module: string, applicationRef: any): Promise<void>;
private bindHandler(instance, metatype, applicationRef, method, path);
private bindHandlerWithProxy(exceptionsHandler, router, middleware, path);
}

View File

@@ -1,46 +1,32 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const invalid_middleware_exception_1 = require("../errors/exceptions/invalid-middleware.exception");
const runtime_exception_1 = require("../errors/exceptions/runtime.exception");
const router_exception_filters_1 = require("../router/router-exception-filters");
const router_proxy_1 = require("../router/router-proxy");
const builder_1 = require("./builder");
const resolver_1 = require("./resolver");
const invalid_middleware_exception_1 = require("../errors/exceptions/invalid-middleware.exception");
const request_method_enum_1 = require("@nestjs/common/enums/request-method.enum");
const routes_mapper_1 = require("./routes-mapper");
const router_proxy_1 = require("../router/router-proxy");
const router_method_factory_1 = require("../helpers/router-method-factory");
const runtime_exception_1 = require("../errors/exceptions/runtime.exception");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const router_exception_filters_1 = require("../router/router-exception-filters");
class MiddlewareModule {
constructor() {
this.routerProxy = new router_proxy_1.RouterProxy();
this.routerMethodFactory = new router_method_factory_1.RouterMethodFactory();
}
register(middlewareContainer, container, config) {
return __awaiter(this, void 0, void 0, function* () {
const appRef = container.getApplicationRef();
this.routerExceptionFilter = new router_exception_filters_1.RouterExceptionFilters(container, config, appRef);
this.routesMapper = new routes_mapper_1.RoutesMapper(container);
this.resolver = new resolver_1.MiddlewareResolver(middlewareContainer);
const modules = container.getModules();
yield this.resolveMiddleware(middlewareContainer, modules);
});
async register(middlewareContainer, container, config) {
const appRef = container.getApplicationRef();
this.routerExceptionFilter = new router_exception_filters_1.RouterExceptionFilters(container, config, appRef);
this.routesMapper = new routes_mapper_1.RoutesMapper(container);
this.resolver = new resolver_1.MiddlewareResolver(middlewareContainer);
this.config = config;
const modules = container.getModules();
await this.resolveMiddleware(middlewareContainer, modules);
}
resolveMiddleware(middlewareContainer, modules) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([...modules.entries()].map(([name, module]) => __awaiter(this, void 0, void 0, function* () {
const instance = module.instance;
this.loadConfiguration(middlewareContainer, instance, name);
yield this.resolver.resolveInstances(module, name);
})));
});
async resolveMiddleware(middlewareContainer, modules) {
await Promise.all([...modules.entries()].map(async ([name, module]) => {
const instance = module.instance;
this.loadConfiguration(middlewareContainer, instance, name);
await this.resolver.resolveInstances(module, name);
}));
}
loadConfiguration(middlewareContainer, instance, module) {
if (!instance.configure)
@@ -52,61 +38,53 @@ class MiddlewareModule {
const config = middlewareBuilder.build();
middlewareContainer.addConfig(config, module);
}
registerMiddleware(middlewareContainer, applicationRef) {
return __awaiter(this, void 0, void 0, function* () {
const configs = middlewareContainer.getConfigs();
const registerAllConfigs = (module, middlewareConfig) => middlewareConfig.map((config) => __awaiter(this, void 0, void 0, function* () {
yield this.registerMiddlewareConfig(middlewareContainer, config, module, applicationRef);
}));
yield Promise.all([...configs.entries()].map(([module, moduleConfigs]) => __awaiter(this, void 0, void 0, function* () {
yield Promise.all(registerAllConfigs(module, [...moduleConfigs]));
})));
async registerMiddleware(middlewareContainer, applicationRef) {
const configs = middlewareContainer.getConfigs();
const registerAllConfigs = (module, middlewareConfig) => middlewareConfig.map(async (config) => {
await this.registerMiddlewareConfig(middlewareContainer, config, module, applicationRef);
});
await Promise.all([...configs.entries()].map(async ([module, moduleConfigs]) => {
await Promise.all(registerAllConfigs(module, [...moduleConfigs]));
}));
}
registerMiddlewareConfig(middlewareContainer, config, module, applicationRef) {
return __awaiter(this, void 0, void 0, function* () {
const { forRoutes } = config;
yield Promise.all(forRoutes.map((routePath) => __awaiter(this, void 0, void 0, function* () {
yield this.registerRouteMiddleware(middlewareContainer, routePath, config, module, applicationRef);
})));
});
async registerMiddlewareConfig(middlewareContainer, config, module, applicationRef) {
const { forRoutes } = config;
await Promise.all(forRoutes.map(async (routeInfo) => {
await this.registerRouteMiddleware(middlewareContainer, routeInfo, config, module, applicationRef);
}));
}
registerRouteMiddleware(middlewareContainer, routePath, config, module, applicationRef) {
return __awaiter(this, void 0, void 0, function* () {
const middlewareCollection = [].concat(config.middleware);
yield Promise.all(middlewareCollection.map((metatype) => __awaiter(this, void 0, void 0, function* () {
const collection = middlewareContainer.getMiddleware(module);
const middleware = collection.get(metatype.name);
if (shared_utils_1.isUndefined(middleware)) {
throw new runtime_exception_1.RuntimeException();
}
const { instance } = middleware;
yield this.bindHandler(instance, metatype, applicationRef, request_method_enum_1.RequestMethod.ALL, routePath);
})));
});
}
bindHandler(instance, metatype, applicationRef, method, path) {
return __awaiter(this, void 0, void 0, function* () {
if (shared_utils_1.isUndefined(instance.resolve)) {
throw new invalid_middleware_exception_1.InvalidMiddlewareException(metatype.name);
async registerRouteMiddleware(middlewareContainer, routeInfo, config, module, applicationRef) {
const middlewareCollection = [].concat(config.middleware);
await Promise.all(middlewareCollection.map(async (metatype) => {
const collection = middlewareContainer.getMiddleware(module);
const middleware = collection.get(metatype.name);
if (shared_utils_1.isUndefined(middleware)) {
throw new runtime_exception_1.RuntimeException();
}
const exceptionsHandler = this.routerExceptionFilter.create(instance, instance.resolve, undefined);
const router = this.routerMethodFactory
.get(applicationRef, method)
.bind(applicationRef);
const bindWithProxy = obj => this.bindHandlerWithProxy(exceptionsHandler, router, obj, path);
const resolve = instance.resolve();
if (!(resolve instanceof Promise)) {
bindWithProxy(resolve);
return;
}
const middleware = yield resolve;
bindWithProxy(middleware);
});
const { instance } = middleware;
await this.bindHandler(instance, metatype, applicationRef, routeInfo.method, routeInfo.path);
}));
}
async bindHandler(instance, metatype, applicationRef, method, path) {
if (shared_utils_1.isUndefined(instance.resolve)) {
throw new invalid_middleware_exception_1.InvalidMiddlewareException(metatype.name);
}
const exceptionsHandler = this.routerExceptionFilter.create(instance, instance.resolve, undefined);
const router = applicationRef.createMiddlewareFactory(method);
const bindWithProxy = middlewareInstance => this.bindHandlerWithProxy(exceptionsHandler, router, middlewareInstance, path);
const resolve = instance.resolve();
if (!(resolve instanceof Promise)) {
bindWithProxy(resolve);
return;
}
const middleware = await resolve;
bindWithProxy(middleware);
}
bindHandlerWithProxy(exceptionsHandler, router, middleware, path) {
const proxy = this.routerProxy.createProxy(middleware, exceptionsHandler);
router(path, proxy);
const prefix = this.config.getGlobalPrefix();
const basePath = prefix ? shared_utils_1.validatePath(prefix) : '';
router(basePath + path, proxy);
}
}
exports.MiddlewareModule = MiddlewareModule;

View File

@@ -1,12 +1,4 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const injector_1 = require("../injector/injector");
class MiddlewareResolver {
@@ -14,16 +6,12 @@ class MiddlewareResolver {
this.middlewareContainer = middlewareContainer;
this.instanceLoader = new injector_1.Injector();
}
resolveInstances(module, moduleName) {
return __awaiter(this, void 0, void 0, function* () {
const middleware = this.middlewareContainer.getMiddleware(moduleName);
yield Promise.all([...middleware.values()].map((wrapper) => __awaiter(this, void 0, void 0, function* () { return yield this.resolveMiddlewareInstance(wrapper, middleware, module); })));
});
async resolveInstances(module, moduleName) {
const middleware = this.middlewareContainer.getMiddleware(moduleName);
await Promise.all([...middleware.values()].map(async (wrapper) => await this.resolveMiddlewareInstance(wrapper, middleware, module)));
}
resolveMiddlewareInstance(wrapper, middleware, module) {
return __awaiter(this, void 0, void 0, function* () {
yield this.instanceLoader.loadInstanceOfMiddleware(wrapper, middleware, module);
});
async resolveMiddlewareInstance(wrapper, middleware, module) {
await this.instanceLoader.loadInstanceOfMiddleware(wrapper, middleware, module);
}
}
exports.MiddlewareResolver = MiddlewareResolver;

View File

@@ -1,11 +1,11 @@
import { RouteInfo, Type } from '@nestjs/common/interfaces';
import 'reflect-metadata';
import { NestContainer } from '../injector/container';
import { Type } from '@nestjs/common/interfaces';
export declare class RoutesMapper {
private readonly routerExplorer;
constructor(container: NestContainer);
mapRouteToRouteProps(route: Type<any> | any | string): string[];
private mapObjectToPath(routeOrPath);
mapRouteToRouteInfo(route: Type<any> | RouteInfo | string): RouteInfo[];
private isRouteInfo(path, objectOrClass);
private validateGlobalPath(path);
private validateRoutePath(path);
}

View File

@@ -1,37 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
const router_explorer_1 = require("../router/router-explorer");
const unknown_request_mapping_exception_1 = require("../errors/exceptions/unknown-request-mapping.exception");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const common_1 = require("@nestjs/common");
const constants_1 = require("@nestjs/common/constants");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
require("reflect-metadata");
const metadata_scanner_1 = require("../metadata-scanner");
const router_explorer_1 = require("../router/router-explorer");
class RoutesMapper {
constructor(container) {
this.routerExplorer = new router_explorer_1.RouterExplorer(new metadata_scanner_1.MetadataScanner(), container);
}
mapRouteToRouteProps(route) {
mapRouteToRouteInfo(route) {
if (shared_utils_1.isString(route)) {
return [route];
return [
{
path: this.validateRoutePath(route),
method: common_1.RequestMethod.ALL,
},
];
}
const routePath = Reflect.getMetadata(constants_1.PATH_METADATA, route);
if (shared_utils_1.isUndefined(routePath)) {
return [this.mapObjectToPath(route)];
if (this.isRouteInfo(routePath, route)) {
return [
{
path: this.validateRoutePath(route.path),
method: route.method,
},
];
}
const paths = this.routerExplorer.scanForPaths(Object.create(route), route.prototype);
const uniquePathsSet = new Set(paths.map(item => this.validateGlobalPath(routePath) +
this.validateRoutePath(item.path)));
return [...uniquePathsSet.values()];
return paths.map(item => ({
path: this.validateGlobalPath(routePath) + this.validateRoutePath(item.path),
method: item.requestMethod,
}));
}
mapObjectToPath(routeOrPath) {
if (shared_utils_1.isString(routeOrPath)) {
return this.validateRoutePath(routeOrPath);
}
const { path } = routeOrPath;
if (shared_utils_1.isUndefined(path)) {
throw new unknown_request_mapping_exception_1.UnknownRequestMappingException();
}
return this.validateRoutePath(path);
isRouteInfo(path, objectOrClass) {
return shared_utils_1.isUndefined(path);
}
validateGlobalPath(path) {
const prefix = shared_utils_1.validatePath(path);

View File

@@ -1,14 +0,0 @@
import { MiddlewareConfiguration } from '@nestjs/common/interfaces/middlewares/middleware-configuration.interface';
import { Type, MiddlewaresConsumer } from '@nestjs/common/interfaces';
import { MiddlewareConfigProxy } from '@nestjs/common/interfaces/middlewares';
import { RoutesMapper } from './routes-mapper';
export declare class MiddlewareBuilder implements MiddlewaresConsumer {
private readonly routesMapper;
private readonly middlewaresCollection;
private readonly logger;
constructor(routesMapper: RoutesMapper);
apply(...middlewares: Array<Type<any> | Function | any>): MiddlewareConfigProxy;
build(): MiddlewareConfiguration[];
private bindValuesToResolve(middlewares, resolveParams);
private static ConfigProxy;
}

View File

@@ -1,52 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const bind_resolve_values_util_1 = require("@nestjs/common/utils/bind-resolve-values.util");
const logger_service_1 = require("@nestjs/common/services/logger.service");
const utils_1 = require("./utils");
const dependencies_decorator_1 = require("@nestjs/common/decorators/core/dependencies.decorator");
class MiddlewareBuilder {
constructor(routesMapper) {
this.routesMapper = routesMapper;
this.middlewaresCollection = new Set();
this.logger = new logger_service_1.Logger(MiddlewareBuilder.name);
}
apply(...middlewares) {
return new MiddlewareBuilder.ConfigProxy(this, dependencies_decorator_1.flatten(middlewares));
}
build() {
return [...this.middlewaresCollection];
}
bindValuesToResolve(middlewares, resolveParams) {
if (shared_utils_1.isNil(resolveParams)) {
return middlewares;
}
const bindArgs = bind_resolve_values_util_1.BindResolveMiddlewareValues(resolveParams);
return [].concat(middlewares).map(bindArgs);
}
}
MiddlewareBuilder.ConfigProxy = class {
constructor(builder, middlewares) {
this.builder = builder;
this.contextParameters = null;
this.includedRoutes = utils_1.filterMiddlewares(middlewares);
}
with(...args) {
this.contextParameters = args;
return this;
}
forRoutes(...routes) {
const { middlewaresCollection, bindValuesToResolve, routesMapper, } = this.builder;
const forRoutes = this.mapRoutesToFlatList(routes.map(route => routesMapper.mapRouteToRouteProps(route)));
const configuration = {
middlewares: bindValuesToResolve(this.includedRoutes, this.contextParameters),
forRoutes,
};
middlewaresCollection.add(configuration);
return this.builder;
}
mapRoutesToFlatList(forRoutes) {
return forRoutes.reduce((a, b) => a.concat(b));
}
};
exports.MiddlewareBuilder = MiddlewareBuilder;

View File

@@ -1,16 +0,0 @@
import { MiddlewareConfiguration } from '@nestjs/common/interfaces/middlewares/middleware-configuration.interface';
import { NestMiddleware } from '@nestjs/common/interfaces/middlewares/nest-middleware.interface';
import { Type } from '@nestjs/common/interfaces/type.interface';
export declare class MiddlewaresContainer {
private readonly middlewares;
private readonly configs;
getMiddlewares(module: string): Map<string, MiddlewareWrapper>;
getConfigs(): Map<string, Set<MiddlewareConfiguration>>;
addConfig(configList: MiddlewareConfiguration[], module: string): void;
private getCurrentMiddlewares(module);
private getCurrentConfig(module);
}
export interface MiddlewareWrapper {
instance: NestMiddleware;
metatype: Type<NestMiddleware>;
}

View File

@@ -1,42 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class MiddlewaresContainer {
constructor() {
this.middlewares = new Map();
this.configs = new Map();
}
getMiddlewares(module) {
return this.middlewares.get(module) || new Map();
}
getConfigs() {
return this.configs;
}
addConfig(configList, module) {
const middlewares = this.getCurrentMiddlewares(module);
const currentConfig = this.getCurrentConfig(module);
const configurations = configList || [];
configurations.map(config => {
[].concat(config.middlewares).map(metatype => {
const token = metatype.name;
middlewares.set(token, {
instance: null,
metatype,
});
});
currentConfig.add(config);
});
}
getCurrentMiddlewares(module) {
if (!this.middlewares.has(module)) {
this.middlewares.set(module, new Map());
}
return this.middlewares.get(module);
}
getCurrentConfig(module) {
if (!this.configs.has(module)) {
this.configs.set(module, new Set());
}
return this.configs.get(module);
}
}
exports.MiddlewaresContainer = MiddlewaresContainer;

View File

@@ -1,21 +0,0 @@
import { NestContainer } from '../injector/container';
import { MiddlewaresContainer } from './container';
import { NestModule } from '@nestjs/common/interfaces/modules/nest-module.interface';
import { MiddlewareConfiguration } from '@nestjs/common/interfaces/middlewares/middleware-configuration.interface';
import { Module } from '../injector/module';
import { ApplicationConfig } from './../application-config';
export declare class MiddlewaresModule {
private readonly routerProxy;
private readonly routerMethodFactory;
private routerExceptionFilter;
private routesMapper;
private resolver;
register(middlewaresContainer: MiddlewaresContainer, container: NestContainer, config: ApplicationConfig): Promise<void>;
resolveMiddlewares(middlewaresContainer: MiddlewaresContainer, modules: Map<string, Module>): Promise<void>;
loadConfiguration(middlewaresContainer: MiddlewaresContainer, instance: NestModule, module: string): void;
registerMiddlewares(middlewaresContainer: MiddlewaresContainer, app: any): Promise<void>;
registerMiddlewareConfig(middlewaresContainer: MiddlewaresContainer, config: MiddlewareConfiguration, module: string, app: any): Promise<void>;
registerRouteMiddleware(middlewaresContainer: MiddlewaresContainer, routePath: string, config: MiddlewareConfiguration, module: string, app: any): Promise<void>;
private setupHandler(instance, metatype, app, method, path);
private setupHandlerWithProxy(exceptionsHandler, router, middleware, path);
}

View File

@@ -1,109 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const builder_1 = require("./builder");
const resolver_1 = require("./resolver");
const invalid_middleware_exception_1 = require("../errors/exceptions/invalid-middleware.exception");
const request_method_enum_1 = require("@nestjs/common/enums/request-method.enum");
const routes_mapper_1 = require("./routes-mapper");
const router_proxy_1 = require("../router/router-proxy");
const router_method_factory_1 = require("../helpers/router-method-factory");
const runtime_exception_1 = require("../errors/exceptions/runtime.exception");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const router_exception_filters_1 = require("./../router/router-exception-filters");
class MiddlewaresModule {
constructor() {
this.routerProxy = new router_proxy_1.RouterProxy();
this.routerMethodFactory = new router_method_factory_1.RouterMethodFactory();
}
register(middlewaresContainer, container, config) {
return __awaiter(this, void 0, void 0, function* () {
const appRef = container.getApplicationRef();
this.routerExceptionFilter = new router_exception_filters_1.RouterExceptionFilters(container, config, appRef);
this.routesMapper = new routes_mapper_1.RoutesMapper(container);
this.resolver = new resolver_1.MiddlewaresResolver(middlewaresContainer);
const modules = container.getModules();
yield this.resolveMiddlewares(middlewaresContainer, modules);
});
}
resolveMiddlewares(middlewaresContainer, modules) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([...modules.entries()].map(([name, module]) => __awaiter(this, void 0, void 0, function* () {
const instance = module.instance;
this.loadConfiguration(middlewaresContainer, instance, name);
yield this.resolver.resolveInstances(module, name);
})));
});
}
loadConfiguration(middlewaresContainer, instance, module) {
if (!instance.configure)
return;
const middlewaresBuilder = new builder_1.MiddlewareBuilder(this.routesMapper);
instance.configure(middlewaresBuilder);
if (!(middlewaresBuilder instanceof builder_1.MiddlewareBuilder))
return;
const config = middlewaresBuilder.build();
middlewaresContainer.addConfig(config, module);
}
registerMiddlewares(middlewaresContainer, app) {
return __awaiter(this, void 0, void 0, function* () {
const configs = middlewaresContainer.getConfigs();
yield Promise.all([...configs.entries()].map(([module, moduleConfigs]) => __awaiter(this, void 0, void 0, function* () {
yield Promise.all([...moduleConfigs].map((config) => __awaiter(this, void 0, void 0, function* () {
yield this.registerMiddlewareConfig(middlewaresContainer, config, module, app);
})));
})));
});
}
registerMiddlewareConfig(middlewaresContainer, config, module, app) {
return __awaiter(this, void 0, void 0, function* () {
const { forRoutes } = config;
yield Promise.all(forRoutes.map((routePath) => __awaiter(this, void 0, void 0, function* () {
yield this.registerRouteMiddleware(middlewaresContainer, routePath, config, module, app);
})));
});
}
registerRouteMiddleware(middlewaresContainer, routePath, config, module, app) {
return __awaiter(this, void 0, void 0, function* () {
const middlewares = [].concat(config.middlewares);
yield Promise.all(middlewares.map((metatype) => __awaiter(this, void 0, void 0, function* () {
const collection = middlewaresContainer.getMiddlewares(module);
const middleware = collection.get(metatype.name);
if (shared_utils_1.isUndefined(middleware)) {
throw new runtime_exception_1.RuntimeException();
}
const { instance } = middleware;
yield this.setupHandler(instance, metatype, app, request_method_enum_1.RequestMethod.ALL, routePath);
})));
});
}
setupHandler(instance, metatype, app, method, path) {
return __awaiter(this, void 0, void 0, function* () {
if (shared_utils_1.isUndefined(instance.resolve)) {
throw new invalid_middleware_exception_1.InvalidMiddlewareException(metatype.name);
}
const exceptionsHandler = this.routerExceptionFilter.create(instance, instance.resolve, undefined);
const router = this.routerMethodFactory.get(app, method).bind(app);
const setupWithProxy = obj => this.setupHandlerWithProxy(exceptionsHandler, router, obj, path);
const resolve = instance.resolve();
if (!(resolve instanceof Promise)) {
setupWithProxy(resolve);
return;
}
const middleware = yield resolve;
setupWithProxy(middleware);
});
}
setupHandlerWithProxy(exceptionsHandler, router, middleware, path) {
const proxy = this.routerProxy.createProxy(middleware, exceptionsHandler);
router(path, proxy);
}
}
exports.MiddlewaresModule = MiddlewaresModule;

View File

@@ -1,9 +0,0 @@
import { MiddlewaresContainer } from './container';
import { Module } from '../injector/module';
export declare class MiddlewaresResolver {
private readonly middlewaresContainer;
private readonly instanceLoader;
constructor(middlewaresContainer: MiddlewaresContainer);
resolveInstances(module: Module, moduleName: string): Promise<void>;
private resolveMiddlewareInstance(wrapper, middlewares, module);
}

View File

@@ -1,29 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const injector_1 = require("../injector/injector");
class MiddlewaresResolver {
constructor(middlewaresContainer) {
this.middlewaresContainer = middlewaresContainer;
this.instanceLoader = new injector_1.Injector();
}
resolveInstances(module, moduleName) {
return __awaiter(this, void 0, void 0, function* () {
const middlewares = this.middlewaresContainer.getMiddlewares(moduleName);
yield Promise.all([...middlewares.values()].map((wrapper) => __awaiter(this, void 0, void 0, function* () { return yield this.resolveMiddlewareInstance(wrapper, middlewares, module); })));
});
}
resolveMiddlewareInstance(wrapper, middlewares, module) {
return __awaiter(this, void 0, void 0, function* () {
yield this.instanceLoader.loadInstanceOfMiddleware(wrapper, middlewares, module);
});
}
}
exports.MiddlewaresResolver = MiddlewaresResolver;

View File

@@ -1,11 +0,0 @@
import 'reflect-metadata';
import { NestContainer } from '../injector/container';
import { Type } from '@nestjs/common/interfaces';
export declare class RoutesMapper {
private readonly routerExplorer;
constructor(container: NestContainer);
mapRouteToRouteProps(route: Type<any> | any | string): string[];
private mapObjectToPath(routeOrPath);
private validateGlobalPath(path);
private validateRoutePath(path);
}

View File

@@ -1,44 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
const router_explorer_1 = require("../router/router-explorer");
const unknown_request_mapping_exception_1 = require("../errors/exceptions/unknown-request-mapping.exception");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const constants_1 = require("@nestjs/common/constants");
const metadata_scanner_1 = require("../metadata-scanner");
class RoutesMapper {
constructor(container) {
this.routerExplorer = new router_explorer_1.RouterExplorer(new metadata_scanner_1.MetadataScanner(), container);
}
mapRouteToRouteProps(route) {
if (shared_utils_1.isString(route)) {
return [route];
}
const routePath = Reflect.getMetadata(constants_1.PATH_METADATA, route);
if (shared_utils_1.isUndefined(routePath)) {
return [this.mapObjectToPath(route)];
}
const paths = this.routerExplorer.scanForPaths(Object.create(route), route.prototype);
const uniquePathsSet = new Set(paths.map(item => this.validateGlobalPath(routePath) +
this.validateRoutePath(item.path)));
return [...uniquePathsSet.values()];
}
mapObjectToPath(routeOrPath) {
if (shared_utils_1.isString(routeOrPath)) {
return this.validateRoutePath(routeOrPath);
}
const { path } = routeOrPath;
if (shared_utils_1.isUndefined(path)) {
throw new unknown_request_mapping_exception_1.UnknownRequestMappingException();
}
return this.validateRoutePath(path);
}
validateGlobalPath(path) {
const prefix = shared_utils_1.validatePath(path);
return prefix === '/' ? '' : prefix;
}
validateRoutePath(path) {
return shared_utils_1.validatePath(path);
}
}
exports.RoutesMapper = RoutesMapper;

View File

@@ -1,5 +0,0 @@
import { Type } from '@nestjs/common/interfaces';
export declare const filterMiddlewares: (middlewares: any) => any[];
export declare const mapToClass: (middleware: any) => any;
export declare const isClass: (middleware: any) => boolean;
export declare const assignToken: (metatype: any) => Type<any>;

View File

@@ -1,27 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
exports.filterMiddlewares = middlewares => {
return []
.concat(middlewares)
.filter(shared_utils_1.isFunction)
.map(middleware => exports.mapToClass(middleware));
};
exports.mapToClass = middleware => {
if (this.isClass(middleware)) {
return middleware;
}
return exports.assignToken(class {
constructor() {
this.resolve = (...args) => (...params) => middleware(...params);
}
});
};
exports.isClass = middleware => {
return middleware.toString().substring(0, 5) === 'class';
};
exports.assignToken = (metatype) => {
this.id = this.id || 1;
Object.defineProperty(metatype, 'name', { value: ++this.id });
return metatype;
};

View File

@@ -1,6 +1,6 @@
import { NestContainer } from './injector/container';
import { Type } from '@nestjs/common/interfaces/type.interface';
import { INestApplicationContext, OnModuleInit } from '@nestjs/common';
import { Type } from '@nestjs/common/interfaces/type.interface';
import { NestContainer } from './injector/container';
import { Module } from './injector/module';
export declare class NestApplicationContext implements INestApplicationContext {
protected readonly container: NestContainer;
@@ -11,14 +11,14 @@ export declare class NestApplicationContext implements INestApplicationContext {
constructor(container: NestContainer, scope: Type<any>[], contextModule: Module);
selectContextModule(): void;
select<T>(module: Type<T>): INestApplicationContext;
get<T>(typeOrToken: Type<T> | string | symbol, options?: {
get<TInput = any, TResult = TInput>(typeOrToken: Type<TInput> | string | symbol, options?: {
strict: boolean;
}): T;
find<T>(typeOrToken: Type<T> | string | symbol): T;
}): TResult;
find<TInput = any, TResult = TInput>(typeOrToken: Type<TInput> | string | symbol): TResult;
init(): Promise<this>;
protected callInitHook(): Promise<any>;
protected callModuleInitHook(module: Module): Promise<any>;
protected hasOnModuleInitHook(instance: any): instance is OnModuleInit;
private findInstanceByPrototypeOrToken<T>(metatypeOrToken, contextModule);
private findInstanceByPrototypeOrToken<TInput, TResult>(metatypeOrToken, contextModule);
private initFlattenModule();
}

View File

@@ -1,18 +1,10 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const iterare_1 = require("iterare");
const module_token_factory_1 = require("./injector/module-token-factory");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const unknown_module_exception_1 = require("./errors/exceptions/unknown-module.exception");
const iterare_1 = require("iterare");
const unknown_element_exception_1 = require("./errors/exceptions/unknown-element.exception");
const unknown_module_exception_1 = require("./errors/exceptions/unknown-module.exception");
const module_token_factory_1 = require("./injector/module-token-factory");
class NestApplicationContext {
constructor(container, scope, contextModule) {
this.container = container;
@@ -45,27 +37,21 @@ class NestApplicationContext {
this.initFlattenModule();
return this.findInstanceByPrototypeOrToken(typeOrToken, this.contextModuleFixture);
}
init() {
return __awaiter(this, void 0, void 0, function* () {
yield this.callInitHook();
return this;
});
async init() {
await this.callInitHook();
return this;
}
callInitHook() {
return __awaiter(this, void 0, void 0, function* () {
const modules = this.container.getModules();
yield Promise.all(iterare_1.default(modules.values()).map((module) => __awaiter(this, void 0, void 0, function* () { return yield this.callModuleInitHook(module); })));
});
async callInitHook() {
const modules = this.container.getModules();
await Promise.all(iterare_1.default(modules.values()).map(async (module) => await this.callModuleInitHook(module)));
}
callModuleInitHook(module) {
return __awaiter(this, void 0, void 0, function* () {
const components = [...module.routes, ...module.components];
yield Promise.all(iterare_1.default(components)
.map(([key, { instance }]) => instance)
.filter(instance => !shared_utils_1.isNil(instance))
.filter(this.hasOnModuleInitHook)
.map((instance) => __awaiter(this, void 0, void 0, function* () { return yield instance.onModuleInit(); })));
});
async callModuleInitHook(module) {
const components = [...module.routes, ...module.components];
await Promise.all(iterare_1.default(components)
.map(([key, { instance }]) => instance)
.filter(instance => !shared_utils_1.isNil(instance))
.filter(this.hasOnModuleInitHook)
.map(async (instance) => await instance.onModuleInit()));
}
hasOnModuleInitHook(instance) {
return !shared_utils_1.isUndefined(instance.onModuleInit);

View File

@@ -1,17 +1,16 @@
/// <reference types="node" />
import * as http from 'http';
import { CanActivate, ExceptionFilter, NestInterceptor, PipeTransform, WebSocketAdapter } from '@nestjs/common';
import { INestApplication, INestMicroservice } from '@nestjs/common';
import { CanActivate, ExceptionFilter, INestApplication, INestMicroservice, NestInterceptor, PipeTransform, WebSocketAdapter } from '@nestjs/common';
import { HttpServer } from '@nestjs/common/interfaces';
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
import { ServeStaticOptions } from '@nestjs/common/interfaces/external/serve-static-options.interface';
import { MicroserviceOptions } from '@nestjs/common/interfaces/microservices/microservice-configuration.interface';
import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface';
import { INestExpressApplication } from '@nestjs/common/interfaces/nest-express-application.interface';
import { INestFastifyApplication } from '@nestjs/common/interfaces/nest-fastify-application.interface';
import * as http from 'http';
import { ApplicationConfig } from './application-config';
import { NestContainer } from './injector/container';
import { NestApplicationContext } from './nest-application-context';
import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface';
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
import { HttpServer } from '@nestjs/common/interfaces';
import { INestExpressApplication } from '@nestjs/common/interfaces/nest-express-application.interface';
import { INestFastifyApplication } from '@nestjs/common/interfaces/nest-fastify-application.interface';
import { ServeStaticOptions } from '@nestjs/common/interfaces/external/serve-static-options.interface';
export declare class NestApplication extends NestApplicationContext implements INestApplication, INestExpressApplication, INestFastifyApplication {
private readonly httpAdapter;
private readonly config;

View File

@@ -1,30 +1,22 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const logger_service_1 = require("@nestjs/common/services/logger.service");
const load_package_util_1 = require("@nestjs/common/utils/load-package.util");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const bodyParser = require("body-parser");
const cors = require("cors");
const http = require("http");
const https = require("https");
const optional = require("optional");
const bodyParser = require("body-parser");
const iterare_1 = require("iterare");
const logger_service_1 = require("@nestjs/common/services/logger.service");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const application_config_1 = require("./application-config");
const constants_1 = require("./constants");
const middleware_module_1 = require("./middleware/middleware-module");
const routes_resolver_1 = require("./router/routes-resolver");
const container_1 = require("./middleware/container");
const nest_application_context_1 = require("./nest-application-context");
const optional = require("optional");
const express_adapter_1 = require("./adapters/express-adapter");
const fastify_adapter_1 = require("./adapters/fastify-adapter");
const load_package_util_1 = require("@nestjs/common/utils/load-package.util");
const application_config_1 = require("./application-config");
const constants_1 = require("./constants");
const container_1 = require("./middleware/container");
const middleware_module_1 = require("./middleware/middleware-module");
const nest_application_context_1 = require("./nest-application-context");
const routes_resolver_1 = require("./router/routes-resolver");
const { SocketModule } = optional('@nestjs/websockets/socket-module') || {};
const { MicroservicesModule } = optional('@nestjs/microservices/microservices-module') || {};
const { IoAdapter } = optional('@nestjs/websockets/adapters/io-adapter') || {};
@@ -80,28 +72,24 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
? this.httpServer
: this.httpAdapter.getHttpServer();
}
registerModules() {
return __awaiter(this, void 0, void 0, function* () {
this.socketModule &&
this.socketModule.register(this.container, this.config);
if (this.microservicesModule) {
this.microservicesModule.register(this.container, this.config);
this.microservicesModule.setupClients(this.container);
}
yield this.middlewareModule.register(this.middlewareContainer, this.container, this.config);
});
async registerModules() {
this.socketModule &&
this.socketModule.register(this.container, this.config);
if (this.microservicesModule) {
this.microservicesModule.register(this.container, this.config);
this.microservicesModule.setupClients(this.container);
}
await this.middlewareModule.register(this.middlewareContainer, this.container, this.config);
}
init() {
return __awaiter(this, void 0, void 0, function* () {
const useBodyParser = this.appOptions && this.appOptions.bodyParser !== false;
useBodyParser && this.registerParserMiddleware();
yield this.registerModules();
yield this.registerRouter();
yield this.callInitHook();
this.isInitialized = true;
this.logger.log(constants_1.messages.APPLICATION_READY);
return this;
});
async init() {
const useBodyParser = this.appOptions && this.appOptions.bodyParser !== false;
useBodyParser && this.registerParserMiddleware();
await this.registerModules();
await this.registerRouter();
await this.callInitHook();
this.isInitialized = true;
this.logger.log(constants_1.messages.APPLICATION_READY);
return this;
}
registerParserMiddleware() {
if (this.httpAdapter instanceof fastify_adapter_1.FastifyAdapter) {
@@ -125,13 +113,11 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
shared_utils_1.isFunction(app._router.stack.filter) &&
!!app._router.stack.filter(layer => layer && layer.handle && layer.handle.name === name).length);
}
registerRouter() {
return __awaiter(this, void 0, void 0, function* () {
yield this.registerMiddleware(this.httpAdapter);
const prefix = this.config.getGlobalPrefix();
const basePath = prefix ? shared_utils_1.validatePath(prefix) : '';
this.routesResolver.resolve(this.httpAdapter, basePath);
});
async registerRouter() {
await this.registerMiddleware(this.httpAdapter);
const prefix = this.config.getGlobalPrefix();
const basePath = prefix ? shared_utils_1.validatePath(prefix) : '';
this.routesResolver.resolve(this.httpAdapter, basePath);
}
connectMicroservice(options) {
const { NestMicroservice } = load_package_util_1.loadPackage('@nestjs/microservices', 'NestFactory');
@@ -201,28 +187,24 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
this.httpAdapter.use(cors(options));
return this;
}
listen(port, ...args) {
return __awaiter(this, void 0, void 0, function* () {
!this.isInitialized && (yield this.init());
this.httpServer.listen(port, ...args);
return this.httpServer;
});
async listen(port, ...args) {
!this.isInitialized && (await this.init());
this.httpServer.listen(port, ...args);
return this.httpServer;
}
listenAsync(port, hostname) {
return new Promise(resolve => {
const server = this.listen(port, hostname, () => resolve(server));
});
}
close() {
return __awaiter(this, void 0, void 0, function* () {
this.socketModule && (yield this.socketModule.close());
this.httpServer && this.httpServer.close();
yield Promise.all(iterare_1.default(this.microservices).map((microservice) => __awaiter(this, void 0, void 0, function* () {
microservice.setIsTerminated(true);
yield microservice.close();
})));
yield this.callDestroyHook();
});
async close() {
this.socketModule && (await this.socketModule.close());
this.httpServer && this.httpServer.close();
await Promise.all(iterare_1.default(this.microservices).map(async (microservice) => {
microservice.setIsTerminated(true);
await microservice.close();
}));
await this.callDestroyHook();
}
setGlobalPrefix(prefix) {
this.config.setGlobalPrefix(prefix);
@@ -265,10 +247,8 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
loadPackage(name, ctx) {
return load_package_util_1.loadPackage(name, ctx);
}
registerMiddleware(instance) {
return __awaiter(this, void 0, void 0, function* () {
yield this.middlewareModule.registerMiddleware(this.middlewareContainer, instance);
});
async registerMiddleware(instance) {
await this.middlewareModule.registerMiddleware(this.middlewareContainer, instance);
}
isExpress() {
const isExpress = !this.httpAdapter.getHttpServer;
@@ -278,25 +258,21 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
return this.httpAdapter instanceof express_adapter_1.ExpressAdapter;
}
listenToPromise(microservice) {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
yield microservice.listen(resolve);
}));
}
callDestroyHook() {
return __awaiter(this, void 0, void 0, function* () {
const modules = this.container.getModules();
yield Promise.all(iterare_1.default(modules.values()).map((module) => __awaiter(this, void 0, void 0, function* () { return yield this.callModuleDestroyHook(module); })));
return new Promise(async (resolve, reject) => {
await microservice.listen(resolve);
});
}
callModuleDestroyHook(module) {
return __awaiter(this, void 0, void 0, function* () {
const components = [...module.routes, ...module.components];
yield Promise.all(iterare_1.default(components)
.map(([key, { instance }]) => instance)
.filter(instance => !shared_utils_1.isNil(instance))
.filter(this.hasOnModuleDestroyHook)
.map((instance) => __awaiter(this, void 0, void 0, function* () { return yield instance.onModuleDestroy(); })));
});
async callDestroyHook() {
const modules = this.container.getModules();
await Promise.all(iterare_1.default(modules.values()).map(async (module) => await this.callModuleDestroyHook(module)));
}
async callModuleDestroyHook(module) {
const components = [...module.routes, ...module.components];
await Promise.all(iterare_1.default(components)
.map(([key, { instance }]) => instance)
.filter(instance => !shared_utils_1.isNil(instance))
.filter(this.hasOnModuleDestroyHook)
.map(async (instance) => await instance.onModuleDestroy()));
}
hasOnModuleDestroyHook(instance) {
return !shared_utils_1.isUndefined(instance.onModuleDestroy);

View File

@@ -1,11 +1,11 @@
import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface';
import { INestApplication, INestMicroservice, INestApplicationContext, HttpServer } from '@nestjs/common';
import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface';
import { NestMicroserviceOptions } from '@nestjs/common/interfaces/microservices/nest-microservice-options.interface';
import { INestExpressApplication } from '@nestjs/common/interfaces/nest-express-application.interface';
import { FastifyAdapter } from './adapters/fastify-adapter';
import { INestFastifyApplication } from '@nestjs/common/interfaces/nest-fastify-application.interface';
import { HttpServer, INestApplication, INestApplicationContext, INestMicroservice } from '@nestjs/common';
import { MicroserviceOptions } from '@nestjs/common/interfaces/microservices/microservice-configuration.interface';
import { NestMicroserviceOptions } from '@nestjs/common/interfaces/microservices/nest-microservice-options.interface';
import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface';
import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface';
import { INestExpressApplication } from '@nestjs/common/interfaces/nest-express-application.interface';
import { INestFastifyApplication } from '@nestjs/common/interfaces/nest-fastify-application.interface';
import { FastifyAdapter } from './adapters/fastify-adapter';
export declare class NestFactoryStatic {
private readonly logger;
/**

View File

@@ -1,45 +1,35 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const scanner_1 = require("./scanner");
const instance_loader_1 = require("./injector/instance-loader");
const container_1 = require("./injector/container");
const exceptions_zone_1 = require("./errors/exceptions-zone");
const logger_service_1 = require("@nestjs/common/services/logger.service");
const constants_1 = require("./constants");
const nest_application_1 = require("./nest-application");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const express_factory_1 = require("./adapters/express-factory");
const metadata_scanner_1 = require("./metadata-scanner");
const nest_application_context_1 = require("./nest-application-context");
const application_config_1 = require("./application-config");
const express_adapter_1 = require("./adapters/express-adapter");
const load_package_util_1 = require("@nestjs/common/utils/load-package.util");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const express_adapter_1 = require("./adapters/express-adapter");
const express_factory_1 = require("./adapters/express-factory");
const application_config_1 = require("./application-config");
const constants_1 = require("./constants");
const exceptions_zone_1 = require("./errors/exceptions-zone");
const container_1 = require("./injector/container");
const instance_loader_1 = require("./injector/instance-loader");
const metadata_scanner_1 = require("./metadata-scanner");
const nest_application_1 = require("./nest-application");
const nest_application_context_1 = require("./nest-application-context");
const scanner_1 = require("./scanner");
class NestFactoryStatic {
constructor() {
this.logger = new logger_service_1.Logger('NestFactory', true);
}
create(module, serverOrOptions, options) {
return __awaiter(this, void 0, void 0, function* () {
const isHttpServer = serverOrOptions && serverOrOptions.patch;
// tslint:disable-next-line:prefer-const
let [httpServer, appOptions] = isHttpServer
? [serverOrOptions, options]
: [express_factory_1.ExpressFactory.create(), serverOrOptions];
const applicationConfig = new application_config_1.ApplicationConfig();
const container = new container_1.NestContainer(applicationConfig);
httpServer = this.applyExpressAdapter(httpServer);
this.applyLogger(appOptions);
yield this.initialize(module, container, applicationConfig, httpServer);
return this.createNestInstance(new nest_application_1.NestApplication(container, httpServer, applicationConfig, appOptions));
});
async create(module, serverOrOptions, options) {
const isHttpServer = serverOrOptions && serverOrOptions.patch;
// tslint:disable-next-line:prefer-const
let [httpServer, appOptions] = isHttpServer
? [serverOrOptions, options]
: [express_factory_1.ExpressFactory.create(), serverOrOptions];
const applicationConfig = new application_config_1.ApplicationConfig();
const container = new container_1.NestContainer(applicationConfig);
httpServer = this.applyExpressAdapter(httpServer);
this.applyLogger(appOptions);
await this.initialize(module, container, applicationConfig, httpServer);
return this.createNestInstance(new nest_application_1.NestApplication(container, httpServer, applicationConfig, appOptions));
}
/**
* Creates an instance of the NestMicroservice
@@ -48,15 +38,13 @@ class NestFactoryStatic {
* @param {NestMicroserviceOptions & MicroserviceOptions} options Optional microservice configuration
* @returns {Promise}
*/
createMicroservice(module, options) {
return __awaiter(this, void 0, void 0, function* () {
const { NestMicroservice } = load_package_util_1.loadPackage('@nestjs/microservices', 'NestFactory');
const applicationConfig = new application_config_1.ApplicationConfig();
const container = new container_1.NestContainer(applicationConfig);
this.applyLogger(options);
yield this.initialize(module, container, applicationConfig);
return this.createNestInstance(new NestMicroservice(container, options, applicationConfig));
});
async createMicroservice(module, options) {
const { NestMicroservice } = load_package_util_1.loadPackage('@nestjs/microservices', 'NestFactory');
const applicationConfig = new application_config_1.ApplicationConfig();
const container = new container_1.NestContainer(applicationConfig);
this.applyLogger(options);
await this.initialize(module, container, applicationConfig);
return this.createNestInstance(new NestMicroservice(container, options, applicationConfig));
}
/**
* Creates an instance of the NestApplicationContext
@@ -65,37 +53,33 @@ class NestFactoryStatic {
* @param {NestApplicationContextOptions} options Optional Nest application configuration
* @returns {Promise}
*/
createApplicationContext(module, options) {
return __awaiter(this, void 0, void 0, function* () {
const container = new container_1.NestContainer();
this.applyLogger(options);
yield this.initialize(module, container);
const modules = container.getModules().values();
const root = modules.next().value;
const context = this.createNestInstance(new nest_application_context_1.NestApplicationContext(container, [], root));
return yield context.init();
});
async createApplicationContext(module, options) {
const container = new container_1.NestContainer();
this.applyLogger(options);
await this.initialize(module, container);
const modules = container.getModules().values();
const root = modules.next().value;
const context = this.createNestInstance(new nest_application_context_1.NestApplicationContext(container, [], root));
return await context.init();
}
createNestInstance(instance) {
return this.createProxy(instance);
}
initialize(module, container, config = new application_config_1.ApplicationConfig(), httpServer = null) {
return __awaiter(this, void 0, void 0, function* () {
const instanceLoader = new instance_loader_1.InstanceLoader(container);
const dependenciesScanner = new scanner_1.DependenciesScanner(container, new metadata_scanner_1.MetadataScanner(), config);
container.setApplicationRef(httpServer);
try {
this.logger.log(constants_1.messages.APPLICATION_START);
yield exceptions_zone_1.ExceptionsZone.asyncRun(() => __awaiter(this, void 0, void 0, function* () {
dependenciesScanner.scan(module);
yield instanceLoader.createInstancesOfDependencies();
dependenciesScanner.applyApplicationProviders();
}));
}
catch (e) {
process.abort();
}
});
async initialize(module, container, config = new application_config_1.ApplicationConfig(), httpServer = null) {
const instanceLoader = new instance_loader_1.InstanceLoader(container);
const dependenciesScanner = new scanner_1.DependenciesScanner(container, new metadata_scanner_1.MetadataScanner(), config);
container.setApplicationRef(httpServer);
try {
this.logger.log(constants_1.messages.APPLICATION_START);
await exceptions_zone_1.ExceptionsZone.asyncRun(async () => {
await dependenciesScanner.scan(module);
await instanceLoader.createInstancesOfDependencies();
dependenciesScanner.applyApplicationProviders();
});
}
catch (e) {
process.abort();
}
}
createProxy(target) {
const proxy = this.createExceptionProxy();

View File

@@ -1,6 +1,6 @@
{
"name": "@nestjs/core",
"version": "5.0.0-rc.2",
"version": "5.1.0",
"description": "Nest - modern, fast, powerful node.js web framework (@core)",
"author": "Kamil Mysliwiec",
"license": "MIT",
@@ -9,6 +9,7 @@
"cors": "2.8.4",
"express": "4.16.3",
"iterare": "0.0.8",
"object-hash": "1.3.0",
"optional": "0.1.4"
},
"peerDependencies": {

View File

@@ -1,35 +1,23 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const params_token_factory_1 = require("./../pipes/params-token-factory");
class PipesConsumer {
constructor() {
this.paramsTokenFactory = new params_token_factory_1.ParamsTokenFactory();
}
apply(value, { metatype, type, data }, transforms) {
return __awaiter(this, void 0, void 0, function* () {
const token = this.paramsTokenFactory.exchangeEnumForString(type);
return yield this.applyPipes(value, { metatype, type: token, data }, transforms);
});
async apply(value, { metatype, type, data }, transforms) {
const token = this.paramsTokenFactory.exchangeEnumForString(type);
return await this.applyPipes(value, { metatype, type: token, data }, transforms);
}
applyPipes(value, { metatype, type, data }, transforms) {
return __awaiter(this, void 0, void 0, function* () {
return yield transforms.reduce((defferedValue, fn) => __awaiter(this, void 0, void 0, function* () {
const val = yield defferedValue;
const result = fn(val, { metatype, type, data });
if (result instanceof Promise) {
return result;
}
return Promise.resolve(result);
}), Promise.resolve(value));
});
async applyPipes(value, { metatype, type, data }, transforms) {
return await transforms.reduce(async (defferedValue, fn) => {
const val = await defferedValue;
const result = fn(val, { metatype, type, data });
if (result instanceof Promise) {
return result;
}
return Promise.resolve(result);
}, Promise.resolve(value));
}
}
exports.PipesConsumer = PipesConsumer;

View File

@@ -1,7 +1,7 @@
import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum';
import { IRouteParamsFactory } from './interfaces/route-params-factory.interface';
export declare class RouteParamsFactory implements IRouteParamsFactory {
exchangeKeyForValue(key: RouteParamtypes | string, data: any, {req, res, next}: {
exchangeKeyForValue(key: RouteParamtypes | string, data: string | object | any, {req, res, next}: {
req: any;
res: any;
next: any;

View File

@@ -21,7 +21,7 @@ class RouteParamsFactory {
case route_paramtypes_enum_1.RouteParamtypes.SESSION:
return req.session;
case route_paramtypes_enum_1.RouteParamtypes.FILE:
return req.file;
return req[data || 'file'];
case route_paramtypes_enum_1.RouteParamtypes.FILES:
return req.files;
default:

View File

@@ -1,11 +1,11 @@
import 'reflect-metadata';
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import { ExceptionsHandler } from '../exceptions/exceptions-handler';
import { RouterProxyCallback } from './../router/router-proxy';
import { ApplicationConfig } from './../application-config';
import { BaseExceptionFilterContext } from '../exceptions/base-exception-filter-context';
import { HttpServer } from '@nestjs/common';
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import 'reflect-metadata';
import { BaseExceptionFilterContext } from '../exceptions/base-exception-filter-context';
import { ExceptionsHandler } from '../exceptions/exceptions-handler';
import { NestContainer } from '../injector/container';
import { ApplicationConfig } from './../application-config';
import { RouterProxyCallback } from './../router/router-proxy';
export declare class RouterExceptionFilters extends BaseExceptionFilterContext {
private readonly config;
private readonly applicationRef;

Some files were not shown because too many files have changed in this diff Show More