Compare commits

..

9 Commits

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

View File

@@ -1,185 +0,0 @@
version: 2
aliases:
- &restore-cache
restore_cache:
key: dependency-cache-{{ checksum "package.json" }}
- &install-deps
run:
name: Install dependencies
command: npm ci
- &build-packages
run:
name: Build
command: npm run build
- &run-unit-tests
run:
name: Test
command: npm run test
unit-tests-template: &unit-tests-template
working_directory: ~/nest
steps:
- checkout
- *restore-cache
- *install-deps
- *build-packages
- *run-unit-tests
jobs:
build:
working_directory: ~/nest
docker:
- image: circleci/node:12
steps:
- checkout
- run:
name: Update NPM version
command: 'sudo npm install -g npm@^8'
- restore_cache:
key: dependency-cache-{{ checksum "package.json" }}
- run:
name: Install dependencies
command: npm ci
- save_cache:
key: dependency-cache-{{ checksum "package.json" }}
paths:
- ./node_modules
- run:
name: Build
command: npm run build
test_node_12:
<<: *unit-tests-template
docker:
- image: circleci/node:12
test_node_14:
<<: *unit-tests-template
docker:
- image: circleci/node:14
test_node_16:
working_directory: ~/nest
docker:
- image: circleci/node:16
steps:
- checkout
- *restore-cache
- *install-deps
- *build-packages
- run:
name: Test (coverage)
command: npm run test:cov
- run:
name: Collect coverage
command: npm run coverage
- store_artifacts:
path: coverage
lint:
working_directory: ~/nest
docker:
- image: circleci/node:16
steps:
- checkout
- *restore-cache
- *install-deps
- run:
name: Lint
command: npm run lint
- run:
name: Lint commit
command: ./node_modules/.bin/commitlint-circle -c .commitlintrc.json
integration_tests:
working_directory: ~/nest
machine: true
steps:
- checkout
- run:
name: Prepare nvm
command: |
echo 'export NVM_DIR="/opt/circleci/.nvm"' >> $BASH_ENV
echo ' [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"' >> $BASH_ENV
- run:
name: Upgrade Node.js
command: |
nvm install v12
node -v
nvm alias default v12
- run:
name: Install Docker Compose
command: |
curl -L https://github.com/docker/compose/releases/download/1.19.0/docker-compose-`uname -s`-`uname -m` > ~/docker-compose
chmod +x ~/docker-compose
sudo mv ~/docker-compose /usr/local/bin/docker-compose
- *install-deps
- run:
name: Prepare tests
command: |
bash ./scripts/prepare.sh
sleep 10
- run:
name: List containers
command: docker ps
- run:
name: Integration tests
command: npm run test:integration
codechecks_benchmarks:
working_directory: ~/nest
docker:
- image: circleci/node:16
steps:
- checkout
- *restore-cache
- *install-deps
- *build-packages
- run:
name: Install native wrk
command: .circleci/install-wrk.sh
- run:
name: Run codechecks with benchmarks
command: yarn codechecks:benchmarks
samples:
working_directory: ~/nest
docker:
- image: circleci/node:16
environment:
- DISABLE_OPENCOLLECTIVE: true
steps:
- checkout
- *restore-cache
- *install-deps
- run:
name: Build all samples
command: npm run build:samples
workflows:
version: 2
build-and-test:
jobs:
- build
- test_node_16:
requires:
- build
- test_node_14:
requires:
- build
- test_node_12:
requires:
- build
- lint:
requires:
- build
- integration_tests:
requires:
- build
- samples:
requires:
- build
- codechecks_benchmarks:
requires:
- build

View File

@@ -1,13 +0,0 @@
#!/usr/bin/env bash
set -e
cd "$(dirname "$0")"
# based on https://medium.com/@felipedutratine/intelligent-benchmark-with-wrk-163986c1587f
cd /tmp/
sudo apt-get install build-essential libssl-dev git -y
git clone https://github.com/wg/wrk.git wrk
cd wrk
sudo make
# move the executable to somewhere in your PATH, ex:
sudo cp wrk /usr/local/bin

View File

@@ -1,44 +0,0 @@
{
"extends": ["@commitlint/config-angular"],
"rules": {
"subject-case": [
2,
"always",
["sentence-case", "start-case", "pascal-case", "upper-case", "lower-case"]
],
"type-enum": [
2,
"always",
[
"build",
"chore",
"ci",
"docs",
"feat",
"fix",
"perf",
"refactor",
"revert",
"style",
"test",
"sample"
]
],
"scope-enum": [
1,
"always",
[
"common",
"core",
"sample",
"microservices",
"express",
"fastify",
"socket.io",
"ws",
"testing",
"websockets"
]
]
}
}

View File

@@ -1,3 +0,0 @@
**/node_modules/**
*.d.ts
*.js

View File

@@ -1,46 +0,0 @@
module.exports = {
root: true,
env: {
node: true,
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'prettier',
],
overrides: [
{
files: ['**/*.ts'],
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/ban-types': 'off',
},
},
{
files: ['**/*.spec.ts', 'integration/**/*.ts'],
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.spec.json',
sourceType: 'module',
},
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/ban-types': 'off',
'@typescript-eslint/no-empty-function': 'off',
},
}
]
};

1
.github/FUNDING.yml vendored
View File

@@ -1,4 +1,3 @@
# These are supported funding model platforms
github: [kamilmysliwiec]
open_collective: nest

41
.github/ISSUE_TEMPLATE/Bug_report.md vendored Normal file
View File

@@ -0,0 +1,41 @@
---
name: "\U0001F41B Bug Report"
about: "If something isn't working as expected \U0001F914."
title: ''
labels: 'type: potential issue :broken_heart:,needs triage'
assignees: ''
---
## Bug Report
## Current behavior
<!-- Describe how the issue manifests. -->
## Input Code
<!-- REPL or Repo link if applicable: -->
```ts
const your = (code) => here;
```
## Expected behavior
<!-- A clear and concise description of what you expected to happen (or code). -->
## Possible Solution
<!--- Only if you have suggestions on a fix for the bug -->
## Environment
<pre><code>
Nest version: X.Y.Z
<!-- Check whether this is still an issue in the most recent Nest version -->
For Tooling issues:
- Node version: XX <!-- run `node --version` -->
- Platform: <!-- Mac, Linux, Windows -->
Others:
<!-- Anything else relevant? Operating system version, IDE, package manager, ... -->
</code></pre>

View File

@@ -1,142 +0,0 @@
name: "\U0001F41B Bug Report"
description: "If something isn't working as expected \U0001F914"
labels: ["needs triage"]
body:
- type: markdown
attributes:
value: |
## :warning: We use GitHub Issues to track bug reports, feature requests and regressions
If you are not sure that your issue is a bug, you could:
- read the [FAQ's common errors](https://docs.nestjs.com/faq/common-errors) page
- use our [Discord community](https://discord.gg/NestJS)
- use [StackOverflow using the tag `nestjs`](https://stackoverflow.com/questions/tagged/nestjs)
- If it's just a quick question you can ping [our Twitter](https://twitter.com/nestframework)
**NOTE:** You don't need to answer questions that you know that aren't relevant.
---
- type: checkboxes
attributes:
label: "Is there an existing issue for this?"
description: "Please search [here](../issues?q=is%3Aissue) to see if an issue already exists for the bug you encountered"
options:
- label: "I have searched the existing issues"
required: true
- type: textarea
validations:
required: true
attributes:
label: "Current behavior"
description: "How the issue manifests?"
- type: input
validations:
required: true
attributes:
label: "Minimum reproduction code"
description: "An URL to some Git repository/[StackBlitz](https://stackblitz.com/fork/github/nestjs/typescript-starter)/[CodeSandbox](https://codesandbox.io/s/github/nestjs/typescript-starter/tree/master) project that reproduces your issue. [Wtf is a minimum reproduction?](https://jmcdo29.github.io/wtf-is-a-minimum-reproduction)"
placeholder: "https://github.com/..."
- type: textarea
attributes:
label: "Steps to reproduce"
description: |
How the issue manifests?
You could leave this blank if you alread write this in your reproduction code
placeholder: |
1. `npm ci`
2. `npm start:dev`
3. See error...
- type: textarea
validations:
required: true
attributes:
label: "Expected behavior"
description: "A clear and concise description of what you expected to happened (or code)"
- type: markdown
attributes:
value: |
---
- type: checkboxes
validations:
required: true
attributes:
label: "Package"
description: |
Which package (or packages) do you think your issue is related to?
**Tip**: The first line of the stack trace can help you to figure out this
The package isn't listed below? Try to find its repository [here](https://github.com/orgs/nestjs/repositories) and open the issue there instead
options:
- label: "I don't know. Or some 3rd-party package"
- label: "<code>@nestjs/common</code>"
- label: "<code>@nestjs/core</code>"
- label: "<code>@nestjs/microservices</code>"
- label: "<code>@nestjs/platform-express</code>"
- label: "<code>@nestjs/platform-fastify</code>"
- label: "<code>@nestjs/platform-socket.io</code>"
- label: "<code>@nestjs/platform-ws</code>"
- label: "<code>@nestjs/testing</code>"
- label: "<code>@nestjs/websockets</code>"
- label: "Other (see below)"
- type: input
attributes:
label: "Other package"
description: "If your issue is related to some package that is not listed above nor under @nestjs org, write its name here"
- type: input
attributes:
label: "NestJS version"
description: |
Which version of `@nestjs/core` are you using?
**Tip**: Make sure that all of yours `@nestjs/*` dependencies are in sync!
placeholder: "8.1.3"
- type: textarea
validations:
required: true
attributes:
label: "Packages versions"
description: |
You could leave your whole `package.json` dependencies list here, or just indicate which version of `@nestjs/*` you are using
**Tip**: run _npx nest info_
value: |
```json
```
- type: input
attributes:
label: "Node.js version"
description: "Which version of Node.js are you using?"
placeholder: "14.17.6"
- type: checkboxes
validations:
required: true
attributes:
label: "In which operating systems have you tested?"
options:
- label: macOS
- label: Windows
- label: Linux
- type: markdown
attributes:
value: |
---
- type: textarea
attributes:
label: "Other"
description: |
Anything else relevant? eg: Logs, OS version, IDE, package manager, etc.
**Tip:** You can attach images, recordings or log files by clicking this area to highlight it and then dragging files in

View File

@@ -0,0 +1,22 @@
---
name: "\U0001F680 Feature Request"
about: "I have a suggestion \U0001F63B!"
title: ''
labels: 'type: enhancement :wolf:,needs triage'
assignees: ''
---
## Feature Request
## Is your feature request related to a problem? Please describe.
<!-- A clear and concise description of what the problem is. Ex. I have an issue when [...] -->
## Describe the solution you'd like
<!-- A clear and concise description of what you want to happen. Add any considered drawbacks. -->
## Teachability, Documentation, Adoption, Migration Strategy
<!-- If you can, explain how users will be able to use this and possibly write out a version the docs. Maybe a screenshot or design? -->
## What is the motivation / use case for changing the behavior?
<!-- Describe the motivation or the concrete use case. -->

View File

@@ -1,55 +0,0 @@
name: "\U0001F680 Feature Request"
description: "I have a suggestion \U0001F63B!"
labels: ["type: enhancement :wolf:", "needs triage"]
body:
- type: markdown
attributes:
value: |
## :warning: We use GitHub Issues to track bug reports, feature requests and regressions
If you are not sure that your issue is a bug, you could:
- read the [FAQ's common errors](https://docs.nestjs.com/faq/common-errors) page
- use our [Discord community](https://discord.gg/NestJS)
- use [StackOverflow using the tag `nestjs`](https://stackoverflow.com/questions/tagged/nestjs)
- If it's just a quick question you can ping [our Twitter](https://twitter.com/nestframework)
---
- type: checkboxes
attributes:
label: "Is there an existing issue that is already proposing this?"
description: "Please search [here](../issues?q=is%3Aissue) to see if an issue already exists for the feature you are requesting"
options:
- label: "I have searched the existing issues"
required: true
- type: textarea
validations:
required: true
attributes:
label: "Is your feature request related to a problem? Please describe it"
description: "A clear and concise description of what the problem is"
placeholder: |
I have an issue when ...
- type: textarea
validations:
required: true
attributes:
label: "Describe the solution you'd like"
description: "A clear and concise description of what you want to happen. Add any considered drawbacks"
- type: textarea
validations:
required: true
attributes:
label: "Teachability, documentation, adoption, migration strategy"
description: "If you can, explain how users will be able to use this and possibly write out a version the docs. Maybe a screenshot or design?"
- type: textarea
validations:
required: true
attributes:
label: "What is the motivation / use case for changing the behavior?"
description: "Describe the motivation or the concrete use case"

40
.github/ISSUE_TEMPLATE/Regression.md vendored Normal file
View File

@@ -0,0 +1,40 @@
---
name: "\U0001F4A5 Regression"
about: Report an unexpected while upgrading your Nest application!
title: ''
labels: 'type: bug :sob:,needs triage'
assignees: ''
---
## Regression
<!-- First check out: https://docs.nestjs.com/migration-guide -->
## Potential Commit/PR that introduced the regression**
<!-- If you have time to investigate, what PR/date introduced this issue. -->
## Describe the regression
<!-- A clear and concise description of what the regression is. -->
## Input Code
<!--- If you have link to our REPL or a standalone repo please link that! -->
```ts
const your = (code) => here;
```
## Expected behavior/code
<!-- A clear and concise description of what you expected to happen (or code). -->
## Environment
<pre><code>
Nest version: A.B.C -> X.Y.Z
For Tooling issues:
- Node version: XX <!-- run `node --version` -->
- Platform: <!-- Mac, Linux, Windows -->
Others:
<!-- Anything else relevant? Operating system version, IDE, package manager, ... -->
</code></pre>

View File

@@ -1,84 +0,0 @@
name: "\U0001F4A5 Regression"
description: "Report an unexpected while upgrading your Nest application!"
labels: ["type: bug :sob:", "needs triage"]
body:
- type: markdown
attributes:
value: |
## :warning: We use GitHub Issues to track bug reports, feature requests and regressions
If you are not sure that your issue is a bug, you could:
- read the [FAQ's common errors](https://docs.nestjs.com/faq/common-errors) page
- use our [Discord community](https://discord.gg/NestJS)
- use [StackOverflow using the tag `nestjs`](https://stackoverflow.com/questions/tagged/nestjs)
- If it's just a quick question you can ping [our Twitter](https://twitter.com/nestframework)
**NOTE:** You don't need to answer questions that you know that aren't relevant.
---
- type: checkboxes
attributes:
label: "Did you read the migration guide?"
description: "Check out the [migration guide here](https://docs.nestjs.com/migration-guide)!"
options:
- label: "I have read the whole migration guide"
required: false
- type: checkboxes
attributes:
label: "Is there an existing issue that is already proposing this?"
description: "Please search [here](../issues?q=is%3Aissue) to see if an issue already exists for the feature you are requesting"
options:
- label: "I have searched the existing issues"
required: true
- type: input
attributes:
label: "Potential Commit/PR that introduced the regression"
description: "If you have time to investigate, what PR/date/version introduced this issue"
placeholder: "PR #123 or commit 5b3c4a4"
- type: input
validations:
required: true
attributes:
label: "NestJS version"
placeholder: "8.1.0 -> 8.1.3"
- type: textarea
validations:
required: true
attributes:
label: "Describe the regression"
description: "A clear and concise description of what the regression is"
- type: input
attributes:
label: "Minimum reproduction code"
description: "An URL to some git repository that reproduces this issue. [Wtf is a minimum reproduction?](https://jmcdo29.github.io/wtf-is-a-minimum-reproduction)"
placeholder: "https://github.com/..."
- type: textarea
attributes:
label: "Input code"
description: "Write some code snippets if you think it is worth it"
value: |
```ts
```
- type: textarea
validations:
required: true
attributes:
label: "Expected behavior"
description: "A clear and concise description of what you expected to happened (or code)"
- type: textarea
attributes:
label: "Other"
description: |
Anything else relevant? eg: Logs, OS version, IDE, package manager, etc.
**Tip:** You can attach images, recordings or log files by clicking this area to highlight it and then dragging files in

View File

@@ -1,48 +0,0 @@
title: "perf: "
name: "\U0001F525 Suggestion for Improving Performance"
description: "I have a suggestion that might improve the performance of Nest \U00002728"
labels: ["type: enhancement :wolf:", "needs triage"]
body:
- type: checkboxes
attributes:
label: "Is there an existing issue that is already proposing this?"
description: "Please search [here](../issues?q=is%3Aissue) to see if an issue already exists for this"
options:
- label: "I have searched the existing issues"
required: true
- type: input
validations:
required: true
attributes:
label: "NestJS version"
description: "Which version do you intend to improve?"
placeholder: "8.1.3"
- type: textarea
attributes:
label: "Is your performance suggestion related to a problem? Please describe it"
description: "A clear and concise description of what the problem is"
- type: textarea
validations:
required: true
attributes:
label: "Describe the performance enhancement you are proposing and how we can try it out"
placeholder: |
Cache `array.length` on the following lines ...
- type: textarea
validations:
required: true
attributes:
label: "Benchmarks result or another proof (eg: POC)"
description: |
If you've already prototyped a solution, share your results here
If not, what makes you believe there will be a performance improvement?
placeholder: |
```
```
MacBook Pro Mid 2014, 2.5 GHz Quad-Core Intel Core i7, 16 GB 1600 MHz DDR3, SSD

View File

@@ -0,0 +1,14 @@
---
name: "\U0001F917 Support Question"
about: "If you have a question \U0001F4AC, please check out our Discord or StackOverflow!"
title: ''
labels: 'type: question 🙌,needs triage'
assignees: ''
---
<!-- We primarily use GitHub as an issue tracker; for usage and support questions, please check out these resources below. Thanks! 😁. -->
* Discord Community Chat: https://discord.gg/G7Qnnhy
* StackOverflow: https://stackoverflow.com/questions/tagged/nestjs using the tag `nestjs`
* Twitter: If it's just a quick question you can ping our Twitter: https://twitter.com/nestframework

View File

@@ -1,10 +0,0 @@
## To encourage contributors to use issue templates, we don't allow blank issues
blank_issues_enabled: false
contact_links:
- name: "\u2049 FAQ"
url: "https://docs.nestjs.com/faq"
about: "Make sure you have read the Frequently Asked Questions page."
- name: "\u2753 Discord Community of NestJS"
url: "https://discord.gg/NestJS"
about: "Please ask support questions or discuss suggestions/enhancements here."

View File

@@ -10,13 +10,15 @@ Please check if your PR fulfills the following requirements:
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:
```
[ ] 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. -->
@@ -28,8 +30,10 @@ Issue Number: N/A
## Does this PR introduce a breaking change?
- [ ] Yes
- [ ] No
```
[ ] Yes
[ ] No
```
<!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. -->

View File

@@ -1,12 +0,0 @@
version: 2
updates:
- package-ecosystem: npm
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10

36
.github/lock.yml vendored
View File

@@ -1,36 +0,0 @@
# Number of days of inactivity before a closed issue or pull request is locked
daysUntilLock: 90
# Skip issues and pull requests created before a given timestamp. Timestamp must
# follow ISO 8601 (`YYYY-MM-DD`). Set to `false` to disable
skipCreatedBefore: false
# Issues and pull requests with these labels will be ignored. Set to `[]` to disable
exemptLabels: []
# Label to add before locking, such as `outdated`. Set to `false` to disable
lockLabel: false
# Comment to post before locking. Set to `false` to disable
lockComment: >
This thread has been automatically locked since there has not been
any recent activity after it was closed. Please open a new issue for
related bugs.
# Assign `resolved` as the reason for locking. Set to `false` to disable
setLockReason: true
# Limit to only `issues` or `pulls`
# only: issues
# Optionally, specify configuration settings just for `issues` or `pulls`
# issues:
# exemptLabels:
# - help-wanted
# lockLabel: outdated
# pulls:
# daysUntilLock: 30
# Repository to extend settings from
# _extends: repo

View File

@@ -1,61 +0,0 @@
name: "CodeQL"
on:
push:
branches: [master, ]
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
schedule:
- cron: '0 17 * * 4'
permissions:
contents: read
jobs:
analyse:
permissions:
security-events: write
name: Analyse
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
queries: +security-extended
# Override language selection by uncommenting this and choosing your languages
# with:
# languages: go, javascript, csharp, python, cpp, java
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2

13
.gitignore vendored
View File

@@ -5,15 +5,6 @@ node_modules/
/.idea
/.awcache
/.vscode
/.devcontainer
*.code-workspace
# Vim
[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-rt-v][a-z]
[._]ss[a-gi-z]
[._]sw[a-p]
# bundle
packages/**/*.d.ts
@@ -27,7 +18,6 @@ yarn-error.log
/**/npm-debug.log
/packages/**/.npmignore
/packages/**/LICENSE
*.tsbuildinfo
# example
/quick-start
@@ -42,6 +32,3 @@ yarn-error.log
/packages/graphql
/benchmarks/memory
build/config\.gypi
.npmrc
pnpm-lock.yaml

View File

@@ -1,4 +0,0 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no-install commitlint --edit $1

View File

@@ -1,4 +0,0 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged

View File

@@ -10,6 +10,4 @@
package-lock.json
tslint.json
tsconfig.json
.prettierrc
*.tsbuildinfo
.prettierrc

View File

@@ -1,3 +1,2 @@
packages/**/*.d.ts
packages/**/*.js
.nyc_output
packages/**/*.js

View File

@@ -1,5 +1,4 @@
{
"singleQuote": true,
"arrowParens": "avoid",
"trailingComma": "all"
}
}

56
.travis.yml Normal file
View File

@@ -0,0 +1,56 @@
language: node_js
cache:
directories:
- "node_modules"
git:
depth: 5
before_install:
- npm i -g npm@latest
install:
- npm ci
- npm run build:dev
jobs:
include:
- state: "Test"
name: "Unit Test Node v12"
script: npm test
node_js: 12
after_success: npm run coverage
- state: "Test"
name: "Unit Test Node v10"
script: npm test
node_js: 10
- state: "Test"
name: "Unit Test Node v8"
script: npm test
node_js: 8
- state: "Test"
name: "Integration Test"
install: skip
before_install: skip
before_script: skip
addons: skip
script:
sudo service mysql stop &&
bash ./scripts/prepare.sh &&
npm run integration-test
node_js: 12
- stage: "Test"
name: "Lint"
script: npm run lint
node_js: 12
- stage: "Test"
name: "Build samples"
script: npm run build:samples
node_js: 12

View File

@@ -1,76 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at support@nestjs.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

View File

@@ -4,14 +4,13 @@ We would love for you to contribute to Nest and help make it even better than it
today! As a contributor, here are the guidelines we would like you to follow:
<!--* [Code of Conduct](#coc)-->
- [Question or Problem?](#question)
- [Issues and Bugs](#issue)
- [Feature Requests](#feature)
- [Submission Guidelines](#submit)
- [Development Setup](#development)
- [Coding Rules](#rules)
- [Commit Message Guidelines](#commit)
* [Question or Problem?](#question)
* [Issues and Bugs](#issue)
* [Feature Requests](#feature)
* [Submission Guidelines](#submit)
* [Development Setup](#development)
* [Coding Rules](#rules)
* [Commit Message Guidelines](#commit)
<!-- - [Signing the CLA](#cla) -->
<!-- ## <a name="coc"></a> Code of Conduct
@@ -19,14 +18,14 @@ Help us keep Nest open and inclusive. Please read and follow our [Code of Conduc
## <a name="question"></a> Got a Question or Problem?
**Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests.** You've got much better chances of getting your question answered on [Stack Overflow][stackoverflow] where the questions should be tagged with tag `nestjs`.
**Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests.** You've got much better chances of getting your question answered on [Stack Overflow](https://stackoverflow.com/questions/tagged/nestjs) where the questions should be tagged with tag `nestjs`.
Stack Overflow is a much better place to ask questions since:
<!-- - there are thousands of people willing to help on Stack Overflow [maybe one day] -->
- questions and answers stay available for public viewing so your question / answer might help someone else
- Stack Overflow's voting system assures that the best answers are prominently visible.
* questions and answers stay available for public viewing so your question / answer might help someone else
* Stack Overflow's voting system assures that the best answers are prominently visible.
To save your and our time, we will systematically close all issues that are requests for general support and redirect people to Stack Overflow.
@@ -45,10 +44,10 @@ Repository. If you would like to _implement_ a new feature, please submit an iss
a proposal for your work first, to be sure that we can use it.
Please consider what kind of change it is:
- For a **Major Feature**, first open an issue and outline your proposal so that it can be
* For a **Major Feature**, first open an issue and outline your proposal so that it can be
discussed. This will also allow us to better coordinate our efforts, prevent duplication of work,
and help you to craft the change so that it is successfully accepted into the project. For your issue name, please prefix your proposal with `[discussion]`, for example "[discussion]: your feature idea".
- **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
## <a name="submit"></a> Submission Guidelines
@@ -58,9 +57,9 @@ Before you submit an issue, please search the issue tracker, maybe an issue for
We want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it. In order to reproduce bugs we will systematically ask you to provide a minimal reproduction scenario using a repository or [Gist](https://gist.github.com/). Having a live, reproducible scenario gives us wealth of important information without going back & forth to you with additional questions like:
- version of NestJS used
- 3rd-party libraries and their versions
- and most importantly - a use-case that fails
* version of NestJS used
* 3rd-party libraries and their versions
* and most importantly - a use-case that fails
<!--
// TODO we need to create a playground, similar to plunkr
@@ -69,9 +68,9 @@ A minimal reproduce scenario using a repository or Gist allows us to quickly con
<!-- We will be insisting on a minimal reproduce scenario in order to save maintainers time and ultimately be able to fix more bugs. Interestingly, from our experience users often find coding problems themselves while preparing a minimal plunk. We understand that sometimes it might be hard to extract essentials bits of code from a larger code-base but we really need to isolate the problem before we can fix it. -->
Unfortunately, we are not able to investigate / fix bugs without a minimal reproduction, so if we don't hear back from you we are going to close an issue that doesn't have enough info to be reproduced.
Unfortunately, we are not able to investigate / fix bugs without a minimal reproduction, so if we don't hear back from you we are going to close an issue that don't have enough info to be reproduced.
You can file new issues by filling out our [new issue form][new_issue].
You can file new issues by filling out our [new issue form](https://github.com/nestjs/nest/issues/new).
### <a name="submit-pr"></a> Submitting a Pull Request (PR)
@@ -84,9 +83,9 @@ To the first point
We cannot accept code without this.
-->
1. Search [GitHub Pull Requests][gh_prs] for an open or closed PR
1. Search [GitHub](https://github.com/nestjs/nest/pulls) for an open or closed PR
that relates to your submission. You don't want to duplicate effort.
1. Fork this repository.
1. Fork the nestjs/nest repo.
1. Make your changes in a new git branch:
```shell
@@ -115,11 +114,11 @@ We cannot accept code without this.
1. In GitHub, send a pull request to `nestjs:master`.
- If we suggest changes then:
* If we suggest changes then:
- Make the required updates.
- Re-run the Nest test suites to ensure tests are still passing.
- Rebase your branch and force push to your GitHub repository (this will update your Pull Request):
* Make the required updates.
* Re-run the Nest test suites to ensure tests are still passing.
* Rebase your branch and force push to your GitHub repository (this will update your Pull Request):
```shell
git rebase master -i
@@ -133,25 +132,25 @@ That's it! Thank you for your contribution!
After your pull request is merged, you can safely delete your branch and pull the changes
from the main (upstream) repository:
- Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows:
* Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows:
```shell
git push origin --delete my-fix-branch
```
- Check out the master branch:
* Check out the master branch:
```shell
git checkout master -f
```
- Delete the local branch:
* Delete the local branch:
```shell
git branch -D my-fix-branch
```
- Update your master with the latest upstream version:
* Update your master with the latest upstream version:
```shell
git pull --ff upstream master
@@ -159,12 +158,12 @@ from the main (upstream) repository:
## <a name="development"></a> Development Setup
You will need [Node.js](https://nodejs.org) version >= 10.13.0 (except for v13).
You will need Node.js version 8.9.0+.
1. After cloning the repo, run:
```bash
$ npm ci # (or yarn install)
$ npm i # (or yarn install)
```
2. In order to prepare your environment run `prepare.sh` shell script:
@@ -173,14 +172,19 @@ $ npm ci # (or yarn install)
$ sh scripts/prepare.sh
```
That will compile fresh packages and afterward, move them all to `sample` directories.
That will compile fresh packages and afterward, move them to all `sample` directories as well as integration tests.
### <a name="common-scripts"></a>Commonly used NPM scripts
```bash
# build all packages and move to "sample" directories
# build all packages and put them near to their source .ts files
$ npm run build
# build all packages and move to "sample" and "integration" directories
# if cross-packages breaking changes were performed you may face irrelevant errors
# in order to verify the build, you can run this command again then
$ npm run build:dev
# run the full unit tests suite
$ npm run test
@@ -190,9 +194,6 @@ $ sh scripts/run-integration.sh
# run linter
$ npm run lint
# build all packages and put them near to their source .ts files
$ npm run build:prod
```
## <a name="rules"></a> Coding Rules
@@ -203,8 +204,8 @@ To ensure consistency throughout the source code, keep these rules in mind as yo
// We're working on auto-documentation.
* All public API methods **must be documented**. (Details TBC). -->
- All features or bug fixes **must be tested** by one or more specs (unit-tests).
- We follow [Google's JavaScript Style Guide][js-style-guide], but wrap all code at
* All features or bug fixes **must be tested** by one or more specs (unit-tests).
* We follow [Google's JavaScript Style Guide][js-style-guide], but wrap all code at
**100 characters**. An automated formatter is available (`npm run format`).
## <a name="commit"></a> Commit Message Guidelines
@@ -228,16 +229,16 @@ format that includes a **type**, a **scope** and a **subject**:
The **header** is mandatory and the **scope** of the header is optional.
Any line of the commit message cannot be longer than 100 characters! This allows the message to be easier
Any line of the commit message cannot be longer 100 characters! This allows the message to be easier
to read on GitHub as well as in various git tools.
Footer should contain a [closing reference to an issue](https://help.github.com/articles/closing-issues-via-commit-messages/) if any.
Samples: (even more [samples][commits_samples])
Samples: (even more [samples](https://github.com/nestjs/nest/commits/master))
```
docs(changelog): update change log to beta.5
fix(core): need to depend on latest rxjs and zone.js
docs(changelog) update change log to beta.5
bugfix(core) need to depend on latest rxjs and zone.js
```
### Revert
@@ -248,51 +249,44 @@ If the commit reverts a previous commit, it should begin with `revert:`, followe
Must be one of the following:
- **build**: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
- **chore**: Updating tasks etc; no production code change
- **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
- **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)
- **test**: Adding missing tests or correcting existing tests
- **sample**: A change to the samples
* **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
* **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)
* **test**: Adding missing tests or correcting existing tests
### Scope
The scope should have the name of the npm package affected (as perceived by person reading changelog generated from commit messages).
The scope should be the name of the npm package affected (as perceived by person reading changelog generated from commit messages.
The following is the list of supported scopes:
- **common**: for changes made on `packages/common` directory
- **core**: for changes made on `packages/core` directory
- **sample**: for changes made on `packages/sample` directory
- **microservices**: for changes made on `packages/microservices` directory
- **express**: for changes made on `packages/platform-express` directory
- **fastify**: for changes made on `packages/platform-fastify` directory
- **socket.io**: for changes made on `packages/platform-socket.io` directory
- **ws**: for changes made on `packages/platform-ws` directory
- **testing**: for changes made on `packages/testing` directory
- **websockets**: for changes made on `packages/websockets` directory
If your change affect more than one package, separate the scopes with a comma (e.g. `common,core`).
* **common**
* **core**
* **sample**
* **microservices**
* **testing**
* **websockets**
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
- **sample/#**: for the example apps directory, replacing # with the example app number
- none/empty string: useful for `style`, `test` and `refactor` changes that are done across all packages (e.g. `style: add missing semicolons`)
* **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
* **sample/#**: for the example apps directory, replacing # with the example app number
* none/empty string: useful for `style`, `test` and `refactor` changes that are done across all packages (e.g. `style: add missing semicolons`)
<!-- * **aio**: used for docs-app (angular.io) related changes within the /aio directory of the repo -->
### Subject
The subject contains succinct description of the change:
- use the imperative, present tense: "change" not "changed" nor "changes"
- don't capitalize first letter
- no dot (.) at the end
* use the imperative, present tense: "change" not "changed" nor "changes"
* don't capitalize first letter
* no dot (.) at the end
### Body
@@ -322,13 +316,14 @@ changes to be accepted, the CLA must be signed. It's a quick process, we promise
<!-- [coc]: https://github.com/angular/code-of-conduct/blob/master/CODE_OF_CONDUCT.md -->
[commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit#
<!-- [individual-cla]: http://code.google.com/legal/individual-cla-v1.0.html -->
<!-- [corporate-cla]: http://code.google.com/legal/corporate-cla-v1.0.html -->
[corporate-cla]: http://code.google.com/legal/corporate-cla-v1.0.html
[dev-doc]: https://github.com/nestjs/nest/blob/master/docs/DEVELOPER.md
[github]: https://github.com/nestjs/nest
[stackoverflow]: https://stackoverflow.com/questions/tagged/nestjs
[discord]: https://discordapp.com/invite/G7Qnnhy
[individual-cla]: http://code.google.com/legal/individual-cla-v1.0.html
[js-style-guide]: https://google.github.io/styleguide/jsguide.html
[new_issue]: https://github.com/nestjs/nest/issues/new
[gh_prs]: https://github.com/nestjs/nest/pulls
[commits_samples]: https://github.com/nestjs/nest/commits/master
[jsfiddle]: http://jsfiddle.net
[plunker]: http://plnkr.co/edit
[runnable]: http://runnable.com
<!-- [stackoverflow]: http://stackoverflow.com/questions/tagged/angular -->

View File

@@ -1,6 +1,6 @@
(The MIT License)
Copyright (c) 2017-2023 Kamil Mysliwiec <https://kamilmysliwiec.com>
Copyright (c) 2017-2019 Kamil Myśliwiec <http://kamilmysliwiec.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

132
Readme.md
View File

@@ -1,21 +1,24 @@
<p align="center">
<a href="https://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
[travis-image]: https://api.travis-ci.org/nestjs/nest.svg?branch=master
[travis-url]: https://travis-ci.org/nestjs/nest
[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
[linux-url]: https://travis-ci.org/nestjs/nest
<p align="center">A progressive <a href="https://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
<a href="https://travis-ci.org/nestjs/nest" target="_blank"><img src="https://api.travis-ci.org/nestjs/nest.svg?branch=master" alt="Travis" /></a>
<a href="https://travis-ci.org/nestjs/nest" target="_blank"><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" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
@@ -30,115 +33,46 @@ Nest is a framework for building efficient, scalable <a href="http://nodejs.org"
## Philosophy
<p>In recent years, thanks to Node.js, JavaScript has become the “lingua franca” of the web for both front and backend applications, giving rise to awesome projects like <a href="https://angular.io/" target="_blank">Angular</a>, <a href="https://github.com/facebook/react" target="_blank">React</a> and <a href="https://github.com/vuejs/vue" target="_blank">Vue</a> which improve developer productivity and enable the construction of fast, testable, extensible frontend applications. However, on the server-side, while there are a lot of superb libraries, helpers and tools for Node, none of them effectively solve the main problem - the architecture.</p>
<p>Nest aims to provide an application architecture out of the box which allows for effortless creation of highly testable, scalable, loosely coupled and easily maintainable applications. The architecture is heavily inspired by Angular.</p>
<p>Nest aims to provide an application architecture out of the box which allows for effortless creation of highly testable, scalable, loosely coupled and easily maintainable applications.</p>
## Getting started
* 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:
* [가이드](readme_kr.md) 문서는 [docs.nestjs.com](https://docs.nestjs.com)에서 확인하실 수 있습니다. :books:
* [ガイド](readme_jp.md)は [docs.nestjs.com](https://docs.nestjs.com)でご確認ください。 :books:
## Questions
For questions and support please use the official [Discord channel](https://discord.gg/G7Qnnhy). The issue list of this repo is **exclusively** for bug reports and feature requests.
## Issues
Please make sure to read the [Issue Reporting Checklist](https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md#-submitting-an-issue) before opening an issue. Issues not conforming to the guidelines may be closed immediately.
## Consulting
With official support, you can get expert help straight from Nest core team. We provide dedicated technical support, migration strategies, advice on best practices (and design decisions), PR reviews, and team augmentation. Read more about [support here](https://enterprise.nestjs.com).
With official support, you can get expert help straight from Nest core team. We provide dedicated technical support, migration strategies, advice on best practices (and design decisions), PR reviews, and team augmentation. Read more about [support here](https://docs.nestjs.com/enterprise).
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support from the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
#### Principal Sponsors
<table style="text-align:center;"><tr>
<td><a href="https://trilon.io" target="_blank"><img src="https://nestjs.com/img/trilon.svg" width="200" valign="middle" /></a></td>
<td><a href="https://www.redhat.com" target="_blank"><img src="https://nestjs.com/img/red-hat-logo.svg" width="200" valign="middle" /></a></td>
<td>
<a href="https://github.com/Sanofi-IADC" target="_blank"><img src="https://docs.nestjs.com/assets/sponsors/sanofi.png" width="180" valign="middle" /></a></td>
<td>
<a href="https://nx.dev" target="_blank"><img src="https://nestjs.com/img/nx-logo.png" height="45" valign="middle" /></a></td>
<td>
<a href="https://valor-software.com/" target="_blank"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="170" valign="middle" /></a></td><td>
<a href="https://amplication.com/" target="_blank"><img src="https://nestjs.com/img/amplication-logo.svg" width="190" valign="middle" /></a></td>
</tr></table>
#### Principal Sponsor
#### Gold Sponsors
<table style="text-align:center;"><tr><td>
<a href="https://weld.app/" target="_blank"><img src="https://nestjs.com/img/weld-logo.svg" width="140" valign="middle" /></a></td>
<td>
<a href="https://intrinsic.ventures/" target="_blank"><img src="https://nestjs.com/img/intrinisic-logo.png" width="210" valign="middle" /></a></td>
<td>
<a href="https://jetbrains.com/" target="_blank"><img src="https://nestjs.com/img/jetbrains-logo.svg" width="110" valign="middle" /></a></td><td>
<a href="https://snyk.co/nestjs" target="_blank"><img src="https://nestjs.com/img/snyk-logo-black.png" width="185" valign="middle" /></a></td><td>
<a href="https://fuseautotech.com/" target="_blank"><img src="https://nestjs.com/img/fuse-logo.svg" width="105" valign="middle" /></a></td>
<td>
<a href="https://ridicorp.com/career/" target="_blank"><img src="https://nestjs.com/img/ridi-logo.svg" width="105" valign="middle" /></a></td><td>
<a href="https://www.movavi.com/imovie-for-windows.html" target="_blank"><img src="https://nestjs.com/img/movavi-logo.svg" width="105" valign="middle" /></a></td></</tr></table>
<a href="https://valor-software.com/" target="_blank"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="320" /></a>
#### Silver Sponsors
<table style="text-align:center;"><tr><td>
<a href="https://neoteric.eu/" target="_blank"><img src="https://nestjs.com/img/neoteric-cut.png" width="120" valign="middle" /></a> </td><td>
<a href="http://gojob.com" target="_blank"><img src="http://nestjs.com/img/gojob-logo.png" valign="middle" width="100" /></a> </td><td>
<a href="https://www.myleodsc.com/" target="_blank"><img src="https://nestjs.com/img/myleo-logo.png" width="180" valign="middle" /></td><td>
<a href="https://careers.meetdandy.com/?gh_src=063ba61e3us" target="_blank"><img src="https://nestjs.com/img/dandy-roles-logo.svg" width="150" valign="middle" /></td><td>
<a href="https://www.castlecraft.in" target="_blank"><img src="https://nestjs.com/img/castlecraft-logo.png" width="150" valign="middle" /></td>
<td><a href="https://www.tinystacks.com" target="_blank"><img src="https://nestjs.com/img/tinystacks-logo.png#1" width="140" valign="middle" /></td>
<td><a href="https://n.inc" target="_blank"><img src="https://nestjs.com/img/n-inc-logo.svg" width="120" valign="middle" /></td></tr><tr>
<td><a href="https://bilberrry.com/" target="_blank"><img src="https://nestjs.com/img/bilberrry-logo.svg" width="180" valign="middle" /></td>
<td><a href="https://ipinfo.ai/" target="_blank"><img src="https://nestjs.com/img/ipinfo-logo.png" width="130" valign="middle" /></td>
<td><a href="https://chax.at" target="_blank"><img src="https://nestjs.com/img/chaxat-logo.png" width="100" valign="middle" /></td></tr>
</table>
<a href="https://neoteric.eu/" target="_blank"><img src="https://nestjs.com/img/neoteric-cut.png" width="120" valign="middle" /></a> &nbsp;
<a href="http://gojob.com" target="_blank"><img src="http://nestjs.com/img/gojob-logo.png" valign="middle" height="95" /></a> &nbsp;
<a href="https://trilon.io" target="_blank"><img src="https://nestjs.com/img/trilon.svg" width="150" valign="middle" /></a> &nbsp;
<a href="http://www.leogistics.com" target="_blank"><img src="https://nestjs.com/img/leogistics-logo.jpeg" width="150" valign="middle" /></a>
#### Sponsors
<table><tr><td align="center" valign="middle">
<a href="https://www.swingdev.io" target="_blank"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="110" valign="middle" /> </a></td><td align="center" valign="middle">
<a href="https://www.novologic.com/" target="_blank"><img src="https://nestjs.com/img/novologic.png" width="110" valign="middle" /></a> </td><td align="center" valign="middle">
<a href="https://ever.co/" target="_blank"><img src="https://nestjs.com/img/ever-logo.png" width="72" valign="middle" /></a> </td><td align="center" valign="middle">
<a href="https://blokt.com" target="_blank"><img src="https://nestjs.com/img/blokt-logo.png" width="120" valign="middle" /></a> </td><td align="center" valign="middle">
<a href="http://architectnow.net/" target="_blank"><img src="https://nestjs.com/img/architectnow.png" width="125" valign="middle" /></a> </td><td align="center" valign="middle">
<a href="https://quander.io/" target="_blank"><img src="https://nestjs.com/img/quander.png" width="100" valign="middle" /></a> </td></tr><tr><td align="center" valign="middle">
<a href="https://mantro.net/" target="_blank"><img src="https://nestjs.com/img/mantro-logo.svg" width="95" valign="middle" /></a> </td><td align="center" valign="middle">
<a href="https://triplebyte.com/" target="_blank"><img src="https://nestjs.com/img/triplebyte.png" width="107" valign="middle" /></a> </td><td align="center" valign="middle">
<a href="https://reposit.co.uk/" target="_blank"><img src="https://nestjs.com/img/reposit-logo.png" width="71" valign="middle" /></a></td><td align="center" valign="middle">
<a href="https://nearpod.com/" target="_blank"><img src="https://nestjs.com/img/nearpod-logo.svg" width="100" valign="middle" /></a> </td><td align="center" valign="middle">
<a href="https://clay.global/" target="_blank"><img src="https://nestjs.com/img/clay-logo.svg" width="75" valign="middle" /></a> </td><td align="center" valign="middle">
<a href="https://firesticktricks.com" target="_blank"><img src="https://nestjs.com/img/firesticktricks-logo.png" width="120" valign="middle" /></a></td></tr><tr><td align="center" valign="middle">
<a href="https://www.codeguesser.co.uk" target="_blank"><img src="https://nestjs.com/img/codeguesser-logo.svg" width="120" valign="middle" /></a> </td><td align="center" valign="middle">
<a href="https://f-a.nz/" target="_blank"><img src="https://nestjs.com/img/franz.svg" width="80" valign="middle" /></a> </td><td align="center" valign="middle">
<a href="https://sparkfabrik.com/" target="_blank"><img src="https://nestjs.com/img/sparkfabrik-logo.png" width="120" valign="middle" /></a></td><td align="center" valign="middle"><a href="https://www.thebigphonestore.co.uk/" target="_blank"><img src="https://nestjs.com/img/the-big-phone-store-logo.png" width="65" valign="middle" /></a></td>
<td align="center" valign="middle">
<a href="https://genuinebee.com/" target="_blank"><img src="https://nestjs.com/img/genuinebee.svg" width="97" valign="middle" /></a> </td>
<td align="center" valign="middle"><a href="https://sanyodigital.com/" target="_blank"><img src="https://nestjs.com/img/sanyo-digital.png" width="130" valign="middle" /></a></td></tr><tr><td align="center" valign="middle"><a href="https://vpn-review.com/vpn-for-torrenting" target="_blank"><img src="https://nestjs.com/img/vpn-review-logo.png" width="85" valign="middle" /></a></td><td align="center" valign="middle"><a href="https://lambda-it.ch/" target="_blank"><img src="https://nestjs.com/img/lambda-it-logo.svg" width="115" valign="middle" /></a></td><td align="center" valign="middle"><a href="https://pickwriters.com/top-10-translation-services" target="_blank"><img src="https://nestjs.com/img/pickwriters-logo.png" width="40" valign="middle" /></a></td><td align="center" valign="middle"><a href="https://thewordpoint.com/services/localization" target="_blank"><img src="https://nestjs.com/img/thewordpoint-logo.png" width="40" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://meercode.io/" target="_blank"><img src="https://nestjs.com/img/meercode-logo.png" width="60" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://www.najlepszeplatformyforex.pl/blog/broker-xtb/" target="_blank"><img src="https://nestjs.com/img/npf-logo.jpg" width="200" valign="middle" /></a></td></tr><tr>
<td align="center" valign="middle"><a href="https://thestandarddaily.com/" target="_blank"><img src="https://nestjs.com/img/the-standard-daily-logo.png" width="180" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://houseofangular.io/" target="_blank"><img src="https://nestjs.com/img/house-of-angular.png" width="100" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://rocketech.it/cases/?utm_source=google&utm_medium=badge&utm_campaign=nestjs" target="_blank"><img src="https://nestjs.com/img/rocketech-logo.svg" width="110" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://www.bystored.com/" target="_blank"><img src="https://nestjs.com/img/stored-logo.svg" width="110" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://studyclerk.com/pay-for-research-paper" target="_blank"><img src="https://nestjs.com/img/studyclerk-logo.png" width="125" valign="middle" /></a></td><td align="center" valign="middle"><a href="https://xyndata.com" target="_blank"><img src="https://nestjs.com/img/xyndata-logo.png" width="125" valign="middle" /></a></td></tr><tr>
<td align="center" valign="middle"><a href="https://www.anonymistic.com/" target="_blank"><img src="https://nestjs.com/img/anonymistic-logo.png" width="125" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://www.naologic.com/" target="_blank"><img src="https://nestjs.com/img/naologic-logo.svg" width="125" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://messaged.com/" target="_blank"><img src="https://nestjs.com/img/messaged-logo.png" width="50" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://triplecore.io" target="_blank"><img src="https://nestjs.com/img/triplecore-logo.svg" width="50" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://klqc.de" target="_blank"><img src="https://nestjs.com/img/klcqcl-logo.png" width="120" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://thecasinowizard.com/bonuses/no-deposit-bonuses/" target="_blank"><img src="https://nestjs.com/img/casinowizard-logo.png" width="120" valign="middle" /></a></td></tr><tr>
<td align="center" valign="middle"><a href="https://polygon-software.ch/" target="_blank"><img src="https://nestjs.com/img/polygon-logo.svg" width="120" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://themobilereality.com/" target="_blank"><img src="https://nestjs.com/img/mobile-reality-logo.png" width="45" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://boringowl.io/" target="_blank"><img src="https://nestjs.com/img/boringowl-logo.svg" width="120" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://www.mobilefactory.jp/" target="_blank"><img src="https://nestjs.com/img/mobilefactory-logo.png" width="100" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://nordbot.app/" target="_blank"><img src="https://nestjs.com/img/nordbot-logo.png" width="120" valign="middle" /></a></td>
<td align="center" valign="middle"><a href="https://doppio.sh/" target="_blank"><img src="https://nestjs.com/img/dopiosh-logo.png" width="50" valign="middle" /></a></td></tr><tr>
<td align="center" valign="middle"><a href="https://www.hingehealth.com/" target="_blank"><img src="https://nestjs.com/img/hinge-health-logo.svg" width="100" valign="middle" /></a></td>
</tr></table>
<a href="https://www.swingdev.io" target="_blank"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="110" valign="middle" /> </a> &nbsp; <a href="https://blueanchor.io/" target="_blank"><img src="https://nestjs.com/img/blueanchor.png" width="150" valign="middle" /></a> &nbsp;
<a href="https://www.novologic.com/" target="_blank"><img src="https://nestjs.com/img/novologic.png" width="110" valign="middle" /></a> &nbsp;
<a href="https://scal.io" target="_blank"><img src="https://nestjs.com/img/scalio-logo.svg" width="80" valign="middle" /></a> &nbsp; <a href="http://angularity.io" target="_blank"><img src="http://angularity.io/media/logo.svg" height="22" valign="middle" /></a> &nbsp; <!--<a href="https://keycdn.com"><img src="https://nestjs.com/img/keycdn.svg" height="30" /></a> &nbsp;--> <a href="https://hostpresto.com" target="_blank"><img src="https://nestjs.com/img/hostpresto.png" height="24" valign="middle" /></a>
<a href="https://ever.co/" target="_blank"><img src="https://nestjs.com/img/ever-logo.png" height="14" valign="middle" /></a> &nbsp;
<a href="https://buddy.works/" target="_blank"><img src="https://nestjs.com/img/buddy-logo.svg" height="25" valign="middle" /></a> &nbsp;
<a href="https://blokt.com" target="_blank"><img src="https://nestjs.com/img/blokt-logo.png" height="25" valign="middle" /></a> &nbsp; <a href="https://genuinebee.com/" target="_blank"><img src="https://nestjs.com/img/genuinebee.svg" height="24" valign="middle" /></a> &nbsp; <a href="http://architectnow.net/" target="_blank"><img src="https://nestjs.com/img/architectnow.png" height="20" valign="middle" /></a> &nbsp; <a href="https://quander.io/" target="_blank"><img src="https://nestjs.com/img/quander.png" height="22" valign="middle" /></a> &nbsp; <a href="https://mantro.net/" target="_blank"><img src="https://nestjs.com/img/mantro-logo.svg" height="19" valign="middle" /></a> &nbsp; <a href="https://triplebyte.com/" target="_blank"><img src="https://nestjs.com/img/triplebyte.png" height="20" valign="middle" /></a> &nbsp;
<a href="https://reposit.co.uk/" target="_blank"><img src="https://nestjs.com/img/reposit-logo.png" height="18" valign="middle" /></a> &nbsp; &nbsp; <a href="https://yakaz.com/" target="_blank"><img src="https://nestjs.com/img/yakaz.png" width="70" valign="middle" /></a> &nbsp;
<a href="https://nearpod.com/" target="_blank"><img src="https://nestjs.com/img/nearpod-logo.svg" width="100" valign="middle" /></a> &nbsp;
<a href="https://clay.global/" target="_blank"><img src="https://nestjs.com/img/clay-logo.svg" width="75" valign="middle" /></a> &nbsp;
<a href="https://firesticktricks.com" target="_blank"><img src="https://nestjs.com/img/firesticktricks-logo.png" width="120" valign="middle" /></a> &nbsp;
<a href="https://www.codeguesser.co.uk" target="_blank"><img src="https://nestjs.com/img/codeguesser-logo.svg" width="120" valign="middle" /></a> &nbsp;
<a href="https://tekhattan.com" target="_blank"><img src="https://nestjs.com/img/tekhattan-logo.png" width="110" valign="middle" /></a>
## Backers
@@ -146,7 +80,7 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
## Stay in touch
* Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
* Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
* Website - [https://nestjs.com](https://nestjs.com/)
* Twitter - [@nestframework](https://twitter.com/nestframework)

View File

@@ -1,5 +0,0 @@
# Security Policy
## Reporting a Vulnerability
Please report security issues to `support@nestjs.com`.

View File

@@ -2,87 +2,47 @@
express
-----------------------
Running 10s test @ http://localhost:3000
1024 connections
┌─────────┬───────┬───────┬───────┬────────┬──────────┬──────────┬────────┐
│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │
├─────────┼───────┼───────┼───────┼────────┼──────────┼──────────┼────────┤
│ Latency │ 55 ms │ 58 ms │ 91 ms │ 138 ms │ 61.88 ms │ 23.95 ms │ 747 ms │
└─────────┴───────┴───────┴───────┴────────┴──────────┴──────────┴────────┘
┌───────────┬─────────┬─────────┬─────────┬─────────┬──────────┬─────────┬─────────┐
│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │
├───────────┼─────────┼─────────┼─────────┼─────────┼──────────┼─────────┼─────────┤
│ Req/Sec │ 8407 │ 8407 │ 17407 │ 17743 │ 16454.41 │ 2716.94 │ 8402 │
├───────────┼─────────┼─────────┼─────────┼─────────┼──────────┼─────────┼─────────┤
│ Bytes/Sec │ 1.81 MB │ 1.81 MB │ 3.74 MB │ 3.81 MB │ 3.54 MB │ 584 kB │ 1.81 MB │
└───────────┴─────────┴─────────┴─────────┴─────────┴──────────┴─────────┴─────────┘
Req/Bytes counts sampled once per second.
165k requests in 10.17s, 35.4 MB read
-----------------------
nest (with "@nestjs/platform-express")
-----------------------
Running 10s test @ http://localhost:3000
1024 connections
┌─────────┬───────┬───────┬───────┬───────┬──────────┬──────────┬────────┐
│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │
├─────────┼───────┼───────┼───────┼───────┼──────────┼──────────┼────────┤
│ Latency │ 61 ms │ 64 ms │ 71 ms │ 94 ms │ 65.44 ms │ 17.35 ms │ 325 ms │
└─────────┴───────┴───────┴───────┴───────┴──────────┴──────────┴────────┘
┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬────────┬─────────┐
│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │
├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼────────┼─────────┤
│ Req/Sec │ 14183 │ 14183 │ 15767 │ 15991 │ 15640 │ 501.13 │ 14182 │
├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼────────┼─────────┤
│ Bytes/Sec │ 3.06 MB │ 3.06 MB │ 3.41 MB │ 3.45 MB │ 3.38 MB │ 108 kB │ 3.06 MB │
└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴────────┴─────────┘
Req/Bytes counts sampled once per second.
156k requests in 10.24s, 33.8 MB read
8 threads and 1024 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 47.78ms 19.09ms 212.47ms 66.94%
Req/Sec 1.31k 268.90 2.07k 72.38%
104687 requests in 10.02s, 21.47MB read
Socket errors: connect 0, read 877, write 0, timeout 0
Requests/sec: 10444.24
Transfer/sec: 2.14MB
-----------------------
fastify
-----------------------
Running 10s test @ http://localhost:3000
1024 connections
┌─────────┬───────┬───────┬───────┬───────┬──────────┬──────────┬─────────┐
│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │
├─────────┼───────┼───────┼───────┼───────┼──────────┼──────────┼─────────┤
│ Latency │ 27 ms │ 30 ms │ 39 ms │ 78 ms │ 31.62 ms │ 26.59 ms │ 1232 ms │
└─────────┴───────┴───────┴───────┴───────┴──────────┴──────────┴─────────┘
┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐
│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │
├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤
│ Req/Sec │ 19935 │ 19935 │ 33247 │ 34111 │ 32030.4 │ 4103.84 │ 19931 │
├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤
│ Bytes/Sec │ 3.03 MB │ 3.03 MB │ 5.05 MB │ 5.19 MB │ 4.87 MB │ 624 kB │ 3.03 MB │
└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘
Req/Bytes counts sampled once per second.
320k requests in 10.18s, 48.7 MB read
8 threads and 1024 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 21.80ms 8.73ms 78.12ms 55.78%
Req/Sec 2.99k 0.92k 5.67k 68.88%
238550 requests in 10.02s, 31.17MB read
Socket errors: connect 0, read 862, write 0, timeout 0
Requests/sec: 23795.79
Transfer/sec: 3.11MB
-----------------------
nest (with "@nestjs/platform-fastify")
nest
-----------------------
Running 10s test @ http://localhost:3000
1024 connections
┌─────────┬───────┬───────┬───────┬───────┬──────────┬──────────┬────────┐
│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │
├─────────┼───────┼───────┼───────┼───────┼──────────┼──────────┼────────┤
│ Latency │ 31 ms │ 33 ms │ 38 ms │ 52 ms │ 34.41 ms │ 11.73 ms │ 245 ms │
└─────────┴───────┴───────┴───────┴───────┴──────────┴──────────┴────────┘
┌───────────┬─────────┬─────────┬────────┬─────────┬─────────┬─────────┬─────────┐
│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │
├───────────┼─────────┼─────────┼────────┼─────────┼─────────┼─────────┼─────────┤
│ Req/Sec │ 24911 │ 24911 │ 30031 │ 30335 │ 29470.4 │ 1564.48 │ 24907 │
├───────────┼─────────┼─────────┼────────┼─────────┼─────────┼─────────┼─────────┤
│ Bytes/Sec │ 3.81 MB │ 3.81 MB │ 4.6 MB │ 4.64 MB │ 4.51 MB │ 239 kB │ 3.81 MB │
└───────────┴─────────┴─────────┴────────┴─────────┴─────────┴─────────┴─────────┘
Req/Bytes counts sampled once per second.
295k requests in 10.17s, 45.1 MB read
8 threads and 1024 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 54.00ms 22.33ms 200.25ms 62.23%
Req/Sec 1.15k 338.60 1.88k 66.12%
91348 requests in 10.05s, 18.82MB read
Socket errors: connect 0, read 983, write 0, timeout 0
Requests/sec: 9093.64
Transfer/sec: 1.87MB
-----------------------
nest-fastify
-----------------------
Running 10s test @ http://localhost:3000
8 threads and 1024 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 29.31ms 11.71ms 101.96ms 70.03%
Req/Sec 2.17k 0.93k 4.12k 63.13%
173241 requests in 10.05s, 22.80MB read
Socket errors: connect 0, read 934, write 0, timeout 0
Requests/sec: 17233.87
Transfer/sec: 2.27MB

View File

@@ -2,6 +2,4 @@
const fastify = require('fastify')();
fastify.get('/', async (req, reply) => reply.send('Hello world'));
fastify.listen({
port: 3000
});
fastify.listen(3000);

14
benchmarks/run.sh Normal file
View File

@@ -0,0 +1,14 @@
#!/usr/bin/env bash
echo 'Library:' $1
node $1 &
pid=$!
sleep 2
wrk 'http://localhost:3000' \
-d 10 \
-c 1024 \
-t 8
kill $pid

23
benchmarks/run_all.sh Normal file
View File

@@ -0,0 +1,23 @@
#!/usr/bin/env bash
: > all_output.txt
lib=(express fastify nest nest-fastify)
for item in ${lib[*]}
do
echo '-----------------------' >> all_output.txt
echo $item >> all_output.txt
echo '-----------------------' >> all_output.txt
node $item &
pid=$!
sleep 2
wrk 'http://localhost:3000' \
-d 10 \
-c 1024 \
-t 8 >> all_output.txt
kill $pid
done

View File

@@ -1,7 +0,0 @@
export const mochaHooks = (): Mocha.RootHookObject => {
return {
async beforeAll(this: Mocha.Context) {
await import('reflect-metadata');
},
};
};

View File

@@ -1,11 +0,0 @@
import { Injectable } from '@nestjs/common';
import { FooService } from './foo.service';
@Injectable()
export class BarService {
constructor(private readonly foo: FooService) {}
bar() {
this.foo.foo();
}
}

View File

@@ -1,8 +0,0 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class FooService {
foo() {
console.log('foo called');
}
}

View File

@@ -1,60 +0,0 @@
import { Test } from '@nestjs/testing';
import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as sinon from 'sinon';
import { BarService } from '../src/bar.service';
import { FooService } from '../src/foo.service';
chai.use(chaiAsPromised);
const { expect } = chai;
describe('Auto-Mocking Bar Deps', () => {
let service: BarService;
let fooService: FooService;
const stub = sinon.stub();
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: [BarService],
})
.useMocker(() => ({ foo: stub }))
.compile();
service = moduleRef.get(BarService);
fooService = moduleRef.get(FooService);
});
it('should be defined', () => {
expect(service).not.to.be.undefined;
expect(fooService).not.to.be.undefined;
});
it('should call bar.bar', () => {
service.bar();
expect(stub.called);
});
});
describe('Auto-Mocking with token in factory', () => {
it('can mock the dependencies', async () => {
const moduleRef = await Test.createTestingModule({
providers: [BarService],
})
.useMocker(token => {
if (token === FooService) {
return { foo: sinon.stub };
}
})
.compile();
const service = moduleRef.get(BarService);
const fooServ = moduleRef.get<{ foo: sinon.SinonStub }>(FooService as any);
service.bar();
expect(fooServ.foo.called);
});
it('cannot mock the dependencies', async () => {
const moduleRef = Test.createTestingModule({
providers: [BarService],
}).useMocker(token => {
if (token === FooService.name + 'something that fails the token') {
return { foo: sinon.stub };
}
}).compile;
expect(moduleRef()).to.eventually.throw();
});
});

View File

@@ -1,40 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"allowJs": true,
"outDir": "./dist",
"paths": {
"@nestjs/common": ["../../packages/common"],
"@nestjs/common/*": ["../../packages/common/*"],
"@nestjs/core": ["../../packages/core"],
"@nestjs/core/*": ["../../packages/core/*"],
"@nestjs/microservices": ["../../packages/microservices"],
"@nestjs/microservices/*": ["../../packages/microservices/*"],
"@nestjs/websockets": ["../../packages/websockets"],
"@nestjs/websockets/*": ["../../packages/websockets/*"],
"@nestjs/testing": ["../../packages/testing"],
"@nestjs/testing/*": ["../../packages/testing/*"],
"@nestjs/platform-express": ["../../packages/platform-express"],
"@nestjs/platform-express/*": ["../../packages/platform-express/*"],
"@nestjs/platform-socket.io": ["../../packages/platform-socket.io"],
"@nestjs/platform-socket.io/*": ["../../packages/platform-socket.io/*"],
"@nestjs/platform-ws": ["../../packages/platform-ws"],
"@nestjs/platform-ws/*": ["../../packages/platform-ws/*"]
}
},
"include": [
"src/**/*",
"e2e/**/*"
],
"exclude": [
"node_modules",
]
}

View File

@@ -1,39 +0,0 @@
import { CACHE_MANAGER, INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AsyncRegisterExtraModule } from '../src/async-register-extra-providers/async-register-extra.module';
import { Cache } from 'cache-manager';
import { assert } from 'chai';
describe('Async Register Extra Providers', () => {
let server;
let app: INestApplication;
let cacheManager: Cache;
before(async () => {
const module = await Test.createTestingModule({
imports: [AsyncRegisterExtraModule],
}).compile();
cacheManager = module.get<Cache>(CACHE_MANAGER);
app = module.createNestApplication();
server = app.getHttpServer();
await app.init();
});
it('should be defined', async () => {
assert.isDefined(cacheManager);
});
it(`should return empty`, async () => {
return request(server).get('/').expect(200, 'Not found');
});
it(`should return data`, async () => {
return request(server).get('/').expect(200, 'value');
});
after(async () => {
await app.close();
});
});

View File

@@ -1,39 +0,0 @@
import { CACHE_MANAGER, INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AsyncRegisterModule } from '../src/async-register/async-register.module';
import { Cache } from 'cache-manager';
import { assert } from 'chai';
describe('Async Register', () => {
let server;
let app: INestApplication;
let cacheManager: Cache;
before(async () => {
const module = await Test.createTestingModule({
imports: [AsyncRegisterModule],
}).compile();
cacheManager = module.get<Cache>(CACHE_MANAGER);
app = module.createNestApplication();
server = app.getHttpServer();
await app.init();
});
it('should be defined', async () => {
assert.isDefined(cacheManager);
});
it(`should return empty`, async () => {
return request(server).get('/').expect(200, 'Not found');
});
it(`should return data`, async () => {
return request(server).get('/').expect(200, 'value');
});
after(async () => {
await app.close();
});
});

View File

@@ -1,35 +0,0 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { CustomTtlModule } from '../src/custom-ttl/custom-ttl.module';
describe('Caching Custom TTL', () => {
let server;
let app: INestApplication;
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [CustomTtlModule],
}).compile();
app = module.createNestApplication();
server = app.getHttpServer();
await app.init();
});
it('should return a differnt value after the TTL is elapsed', async () => {
await request(server).get('/').expect(200, '0');
await new Promise(resolve => setTimeout(resolve, 500));
await request(server).get('/').expect(200, '1');
});
it('should return the cached value within the TTL', async () => {
await request(server).get('/').expect(200, '0');
await new Promise(resolve => setTimeout(resolve, 200));
await request(server).get('/').expect(200, '0');
});
afterEach(async () => {
await app.close();
});
});

View File

@@ -1,31 +0,0 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { MultiStoreModule } from '../src/multi-store/multi-store.module';
describe('Caching Multi Store', () => {
let server;
let app: INestApplication;
before(async () => {
const module = await Test.createTestingModule({
imports: [MultiStoreModule],
}).compile();
app = module.createNestApplication();
server = app.getHttpServer();
await app.init();
});
it(`should return empty`, async () => {
return request(server).get('/').expect(200, '');
});
it(`should return data`, async () => {
return request(server).get('/').expect(200, 'multi-store-value');
});
after(async () => {
await app.close();
});
});

View File

@@ -1,16 +0,0 @@
import { Controller, Get, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';
@Controller()
export class AsyncRegisterExtraController {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
@Get()
async getFromStore(): Promise<string> {
const value: string | undefined = await this.cacheManager.get('key');
if (!value) {
await this.cacheManager.set('key', 'value');
}
return value ?? 'Not found';
}
}

View File

@@ -1,16 +0,0 @@
import { CacheModule, Module } from '@nestjs/common';
import { AsyncRegisterExtraController } from './async-register-extra.controller';
import { CacheConfig } from './config/cache.config';
import { ConfigModule } from './config/config.module';
@Module({
imports: [
CacheModule.registerAsync({
extraProviders: [ConfigModule],
isGlobal: true,
useClass: CacheConfig,
}),
],
controllers: [AsyncRegisterExtraController],
})
export class AsyncRegisterExtraModule {}

View File

@@ -1,17 +0,0 @@
import {
CacheModuleOptions,
CacheOptionsFactory,
Injectable,
} from '@nestjs/common';
import { ConfigService } from './config.service';
@Injectable()
export class CacheConfig implements CacheOptionsFactory {
constructor(private readonly configService: ConfigService) {}
createCacheOptions(): CacheModuleOptions {
const ttl = this.configService.getTtl();
return { ttl };
}
}

View File

@@ -1,8 +0,0 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class ConfigService {
public getTtl(): number {
return 10;
}
}

View File

@@ -1,40 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"allowJs": true,
"outDir": "./dist",
"paths": {
"@nestjs/common": ["../../packages/common"],
"@nestjs/common/*": ["../../packages/common/*"],
"@nestjs/core": ["../../packages/core"],
"@nestjs/core/*": ["../../packages/core/*"],
"@nestjs/microservices": ["../../packages/microservices"],
"@nestjs/microservices/*": ["../../packages/microservices/*"],
"@nestjs/websockets": ["../../packages/websockets"],
"@nestjs/websockets/*": ["../../packages/websockets/*"],
"@nestjs/testing": ["../../packages/testing"],
"@nestjs/testing/*": ["../../packages/testing/*"],
"@nestjs/platform-express": ["../../packages/platform-express"],
"@nestjs/platform-express/*": ["../../packages/platform-express/*"],
"@nestjs/platform-socket.io": ["../../packages/platform-socket.io"],
"@nestjs/platform-socket.io/*": ["../../packages/platform-socket.io/*"],
"@nestjs/platform-ws": ["../../packages/platform-ws"],
"@nestjs/platform-ws/*": ["../../packages/platform-ws/*"]
}
},
"include": [
"src/**/*",
"e2e/**/*"
],
"exclude": [
"node_modules",
]
}

View File

@@ -1,16 +0,0 @@
import { Controller, Get, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';
@Controller()
export class AsyncRegisterController {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
@Get()
async getFromStore(): Promise<string> {
const value: string | undefined = await this.cacheManager.get('key');
if (!value) {
await this.cacheManager.set('key', 'value');
}
return value ?? 'Not found';
}
}

View File

@@ -1,14 +0,0 @@
import { CacheModule, Module } from '@nestjs/common';
import { AsyncRegisterController } from './async-register.controller';
import { CacheConfig } from './config/cache.config';
@Module({
imports: [
CacheModule.registerAsync({
isGlobal: true,
useClass: CacheConfig,
}),
],
controllers: [AsyncRegisterController],
})
export class AsyncRegisterModule {}

View File

@@ -1,14 +0,0 @@
import {
CacheModuleOptions,
CacheOptionsFactory,
Injectable,
} from '@nestjs/common';
@Injectable()
export class CacheConfig implements CacheOptionsFactory {
createCacheOptions(): CacheModuleOptions {
const ttl = 100;
return { ttl };
}
}

View File

@@ -1,40 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"allowJs": true,
"outDir": "./dist",
"paths": {
"@nestjs/common": ["../../packages/common"],
"@nestjs/common/*": ["../../packages/common/*"],
"@nestjs/core": ["../../packages/core"],
"@nestjs/core/*": ["../../packages/core/*"],
"@nestjs/microservices": ["../../packages/microservices"],
"@nestjs/microservices/*": ["../../packages/microservices/*"],
"@nestjs/websockets": ["../../packages/websockets"],
"@nestjs/websockets/*": ["../../packages/websockets/*"],
"@nestjs/testing": ["../../packages/testing"],
"@nestjs/testing/*": ["../../packages/testing/*"],
"@nestjs/platform-express": ["../../packages/platform-express"],
"@nestjs/platform-express/*": ["../../packages/platform-express/*"],
"@nestjs/platform-socket.io": ["../../packages/platform-socket.io"],
"@nestjs/platform-socket.io/*": ["../../packages/platform-socket.io/*"],
"@nestjs/platform-ws": ["../../packages/platform-ws"],
"@nestjs/platform-ws/*": ["../../packages/platform-ws/*"]
}
},
"include": [
"src/**/*",
"e2e/**/*"
],
"exclude": [
"node_modules",
]
}

View File

@@ -1,20 +0,0 @@
import {
CacheInterceptor,
CacheTTL,
Controller,
Get,
UseInterceptors,
} from '@nestjs/common';
@Controller()
export class CustomTtlController {
counter = 0;
constructor() {}
@Get()
@CacheTTL(500)
@UseInterceptors(CacheInterceptor)
getNumber() {
return this.counter++;
}
}

View File

@@ -1,8 +0,0 @@
import { CacheModule, Module } from '@nestjs/common';
import { CustomTtlController } from './custom-ttl.controller';
@Module({
imports: [CacheModule.register()],
controllers: [CustomTtlController],
})
export class CustomTtlModule {}

View File

@@ -1,40 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"allowJs": true,
"outDir": "./dist",
"paths": {
"@nestjs/common": ["../../packages/common"],
"@nestjs/common/*": ["../../packages/common/*"],
"@nestjs/core": ["../../packages/core"],
"@nestjs/core/*": ["../../packages/core/*"],
"@nestjs/microservices": ["../../packages/microservices"],
"@nestjs/microservices/*": ["../../packages/microservices/*"],
"@nestjs/websockets": ["../../packages/websockets"],
"@nestjs/websockets/*": ["../../packages/websockets/*"],
"@nestjs/testing": ["../../packages/testing"],
"@nestjs/testing/*": ["../../packages/testing/*"],
"@nestjs/platform-express": ["../../packages/platform-express"],
"@nestjs/platform-express/*": ["../../packages/platform-express/*"],
"@nestjs/platform-socket.io": ["../../packages/platform-socket.io"],
"@nestjs/platform-socket.io/*": ["../../packages/platform-socket.io/*"],
"@nestjs/platform-ws": ["../../packages/platform-ws"],
"@nestjs/platform-ws/*": ["../../packages/platform-ws/*"]
}
},
"include": [
"src/**/*",
"e2e/**/*"
],
"exclude": [
"node_modules",
]
}

View File

@@ -1,16 +0,0 @@
import { Controller, Get, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';
@Controller()
export class MultiStoreController {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
@Get()
async getFromMultiStore(): Promise<unknown> {
const value = await this.cacheManager.get('multi-store-key');
if (!value) {
await this.cacheManager.set('multi-store-key', 'multi-store-value');
}
return value;
}
}

View File

@@ -1,24 +0,0 @@
import { CacheModule, Module } from '@nestjs/common';
import { redisStore } from 'cache-manager-redis-store';
import { MultiStoreController } from './multi-store.controller';
@Module({
imports: [
CacheModule.register([
{
store: 'memory',
max: 100,
ttl: 10,
},
{
store: redisStore,
host: 'localhost',
port: 6379,
db: 0,
ttl: 600,
},
]),
],
controllers: [MultiStoreController],
})
export class MultiStoreModule {}

View File

@@ -1,40 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"allowJs": true,
"outDir": "./dist",
"paths": {
"@nestjs/common": ["../../packages/common"],
"@nestjs/common/*": ["../../packages/common/*"],
"@nestjs/core": ["../../packages/core"],
"@nestjs/core/*": ["../../packages/core/*"],
"@nestjs/microservices": ["../../packages/microservices"],
"@nestjs/microservices/*": ["../../packages/microservices/*"],
"@nestjs/websockets": ["../../packages/websockets"],
"@nestjs/websockets/*": ["../../packages/websockets/*"],
"@nestjs/testing": ["../../packages/testing"],
"@nestjs/testing/*": ["../../packages/testing/*"],
"@nestjs/platform-express": ["../../packages/platform-express"],
"@nestjs/platform-express/*": ["../../packages/platform-express/*"],
"@nestjs/platform-socket.io": ["../../packages/platform-socket.io"],
"@nestjs/platform-socket.io/*": ["../../packages/platform-socket.io/*"],
"@nestjs/platform-ws": ["../../packages/platform-ws"],
"@nestjs/platform-ws/*": ["../../packages/platform-ws/*"]
}
},
"include": [
"src/**/*",
"e2e/**/*"
],
"exclude": [
"node_modules",
]
}

View File

@@ -1,177 +0,0 @@
import { NestExpressApplication } from '@nestjs/platform-express';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
describe('Express Cors', () => {
let app: NestExpressApplication;
const configs = [
{
origin: 'example.com',
methods: 'GET',
credentials: true,
exposedHeaders: ['foo', 'bar'],
allowedHeaders: ['baz', 'woo'],
maxAge: 123,
},
{
origin: 'sample.com',
methods: 'GET',
credentials: true,
exposedHeaders: ['zoo', 'bar'],
allowedHeaders: ['baz', 'foo'],
maxAge: 321,
},
];
describe('Dynamic config', () => {
describe('enableCors', () => {
before(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = module.createNestApplication<NestExpressApplication>();
let requestId = 0;
const configDelegation = function (req, cb) {
const config = configs[requestId];
requestId++;
cb(null, config);
};
app.enableCors(configDelegation);
await app.init();
});
it(`should add cors headers based on the first config`, async () => {
return request(app.getHttpServer())
.get('/')
.expect('access-control-allow-origin', 'example.com')
.expect('vary', 'Origin')
.expect('access-control-allow-credentials', 'true')
.expect('access-control-expose-headers', 'foo,bar')
.expect('content-length', '0');
});
it(`should add cors headers based on the second config`, async () => {
return request(app.getHttpServer())
.options('/')
.expect('access-control-allow-origin', 'sample.com')
.expect('vary', 'Origin')
.expect('access-control-allow-credentials', 'true')
.expect('access-control-expose-headers', 'zoo,bar')
.expect('access-control-allow-methods', 'GET')
.expect('access-control-allow-headers', 'baz,foo')
.expect('access-control-max-age', '321')
.expect('content-length', '0');
});
after(async () => {
await app.close();
});
});
describe('Application Options', () => {
before(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
let requestId = 0;
const configDelegation = function (req, cb) {
const config = configs[requestId];
requestId++;
cb(null, config);
};
app = module.createNestApplication<NestExpressApplication>({
cors: configDelegation,
});
await app.init();
});
it(`should add cors headers based on the first config`, async () => {
return request(app.getHttpServer())
.get('/')
.expect('access-control-allow-origin', 'example.com')
.expect('vary', 'Origin')
.expect('access-control-allow-credentials', 'true')
.expect('access-control-expose-headers', 'foo,bar')
.expect('content-length', '0');
});
it(`should add cors headers based on the second config`, async () => {
return request(app.getHttpServer())
.options('/')
.expect('access-control-allow-origin', 'sample.com')
.expect('vary', 'Origin')
.expect('access-control-allow-credentials', 'true')
.expect('access-control-expose-headers', 'zoo,bar')
.expect('access-control-allow-methods', 'GET')
.expect('access-control-allow-headers', 'baz,foo')
.expect('access-control-max-age', '321')
.expect('content-length', '0');
});
after(async () => {
await app.close();
});
});
});
describe('Static config', () => {
describe('enableCors', () => {
before(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = module.createNestApplication<NestExpressApplication>();
app.enableCors(configs[0]);
await app.init();
});
it(`CORS headers`, async () => {
return request(app.getHttpServer())
.get('/')
.expect('access-control-allow-origin', 'example.com')
.expect('vary', 'Origin')
.expect('access-control-allow-credentials', 'true')
.expect('access-control-expose-headers', 'foo,bar')
.expect('content-length', '0');
});
});
after(async () => {
await app.close();
});
describe('Application Options', () => {
before(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = module.createNestApplication<NestExpressApplication>({
cors: configs[0],
});
await app.init();
});
it(`CORS headers`, async () => {
return request(app.getHttpServer())
.get('/')
.expect('access-control-allow-origin', 'example.com')
.expect('vary', 'Origin')
.expect('access-control-allow-credentials', 'true')
.expect('access-control-expose-headers', 'foo,bar')
.expect('content-length', '0');
});
after(async () => {
await app.close();
});
});
});
});

View File

@@ -1,191 +0,0 @@
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
describe.skip('Fastify Cors', () => {
let app: NestFastifyApplication;
const configs = [
{
origin: 'example.com',
methods: 'GET',
credentials: true,
exposedHeaders: ['foo', 'bar'],
allowedHeaders: ['baz', 'woo'],
maxAge: 123,
},
{
origin: 'sample.com',
methods: 'GET',
credentials: true,
exposedHeaders: ['zoo', 'bar'],
allowedHeaders: ['baz', 'foo'],
maxAge: 321,
},
];
describe('Dynamic config', () => {
describe('enableCors', () => {
before(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = module.createNestApplication<NestFastifyApplication>(
new FastifyAdapter(),
);
let requestId = 0;
const configDelegation = function (req, cb) {
const config = configs[requestId];
requestId++;
cb(null, config);
};
app.enableCors(configDelegation);
await app.init();
});
it(`should add cors headers based on the first config`, async () => {
return request(app.getHttpServer())
.get('/')
.expect('access-control-allow-origin', 'example.com')
.expect('vary', 'Origin')
.expect('access-control-allow-credentials', 'true')
.expect('access-control-expose-headers', 'foo,bar')
.expect('content-length', '0');
});
it(`should add cors headers based on the second config`, async () => {
return request(app.getHttpServer())
.options('/')
.expect('access-control-allow-origin', 'sample.com')
.expect('vary', 'Origin')
.expect('access-control-allow-credentials', 'true')
.expect('access-control-expose-headers', 'zoo,bar')
.expect('access-control-allow-methods', 'GET')
.expect('access-control-allow-headers', 'baz,foo')
.expect('access-control-max-age', '321')
.expect('content-length', '0');
});
after(async () => {
await app.close();
});
});
describe('Application Options', () => {
before(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
let requestId = 0;
const configDelegation = function (req, cb) {
const config = configs[requestId];
requestId++;
cb(null, config);
};
app = module.createNestApplication<NestFastifyApplication>(
new FastifyAdapter(),
{
cors: configDelegation,
},
);
await app.init();
});
it(`should add cors headers based on the first config`, async () => {
return request(app.getHttpServer())
.get('/')
.expect('access-control-allow-origin', 'example.com')
.expect('vary', 'Origin')
.expect('access-control-allow-credentials', 'true')
.expect('access-control-expose-headers', 'foo,bar')
.expect('content-length', '0');
});
it(`should add cors headers based on the second config`, async () => {
return request(app.getHttpServer())
.options('/')
.expect('access-control-allow-origin', 'sample.com')
.expect('vary', 'Origin')
.expect('access-control-allow-credentials', 'true')
.expect('access-control-expose-headers', 'zoo,bar')
.expect('access-control-allow-methods', 'GET')
.expect('access-control-allow-headers', 'baz,foo')
.expect('access-control-max-age', '321')
.expect('content-length', '0');
});
after(async () => {
await app.close();
});
});
});
describe('Static config', () => {
describe('enableCors', () => {
before(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = module.createNestApplication<NestFastifyApplication>(
new FastifyAdapter(),
);
app.enableCors(configs[0]);
await app.init();
});
it(`CORS headers`, async () => {
return request(app.getHttpServer())
.get('/')
.expect('access-control-allow-origin', 'example.com')
.expect('vary', 'Origin')
.expect('access-control-allow-credentials', 'true')
.expect('access-control-expose-headers', 'foo,bar')
.expect('content-length', '0');
});
});
after(async () => {
await app.close();
});
describe('Application Options', () => {
before(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = module.createNestApplication<NestFastifyApplication>(
new FastifyAdapter(),
{
cors: configs[0],
},
);
await app.init();
});
it(`CORS headers`, async () => {
return request(app.getHttpServer())
.get('/')
.expect('access-control-allow-origin', 'example.com')
.expect('vary', 'Origin')
.expect('access-control-allow-credentials', 'true')
.expect('access-control-expose-headers', 'foo,bar')
.expect('content-length', '0');
});
});
after(async () => {
await app.close();
});
});
});

View File

@@ -1,9 +0,0 @@
import { Controller, Get } from '@nestjs/common';
@Controller()
export class AppController {
@Get()
getGlobals() {
return '';
}
}

View File

@@ -1,7 +0,0 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
@Module({
controllers: [AppController],
})
export class AppModule {}

View File

@@ -1,40 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"allowJs": true,
"outDir": "./dist",
"paths": {
"@nestjs/common": ["../../packages/common"],
"@nestjs/common/*": ["../../packages/common/*"],
"@nestjs/core": ["../../packages/core"],
"@nestjs/core/*": ["../../packages/core/*"],
"@nestjs/microservices": ["../../packages/microservices"],
"@nestjs/microservices/*": ["../../packages/microservices/*"],
"@nestjs/websockets": ["../../packages/websockets"],
"@nestjs/websockets/*": ["../../packages/websockets/*"],
"@nestjs/testing": ["../../packages/testing"],
"@nestjs/testing/*": ["../../packages/testing/*"],
"@nestjs/platform-express": ["../../packages/platform-express"],
"@nestjs/platform-express/*": ["../../packages/platform-express/*"],
"@nestjs/platform-socket.io": ["../../packages/platform-socket.io"],
"@nestjs/platform-socket.io/*": ["../../packages/platform-socket.io/*"],
"@nestjs/platform-ws": ["../../packages/platform-ws"],
"@nestjs/platform-ws/*": ["../../packages/platform-ws/*"]
}
},
"include": [
"src/**/*",
"e2e/**/*"
],
"exclude": [
"node_modules",
]
}

View File

@@ -17,15 +17,13 @@ services:
restart: always
mqtt:
container_name: test-mqtt
image: eclipse-mosquitto
volumes:
- ./mosquitto.conf:/mosquitto/config/mosquitto.conf
image: toke/mosquitto
ports:
- "1883:1883"
- "9001:9001"
restart: always
mysql:
image: mysql:8.0.32
image: mysql:5.7.27
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: test
@@ -33,43 +31,15 @@ services:
- "3306:3306"
restart: always
mongodb:
container_name: test-mongodb
image: mongo:latest
environment:
- MONGODB_DATABASE="test"
ports:
- 27017:27017
rabbit:
container_name: test-rabbit
hostname: rabbit
image: "rabbitmq:management"
ports:
- "15672:15672"
- "5672:5672"
tty: true
zookeeper:
container_name: test-zookeeper
hostname: zookeeper
image: confluentinc/cp-zookeeper:7.3.2
ports:
- "2181:2181"
environment:
ZOOKEEPER_CLIENT_PORT: 2181
ZOOKEEPER_TICK_TIME: 2000
kafka:
container_name: test-kafka
hostname: kafka
image: confluentinc/cp-kafka:7.3.2
depends_on:
- zookeeper
ports:
- "29092:29092"
- "9092:9092"
environment:
KAFKA_BROKER_ID: 1
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
KAFKA_DELETE_TOPIC_ENABLE: 'true'

View File

@@ -1,58 +0,0 @@
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
describe('GraphQL Pipes', () => {
let app: INestApplication;
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = module.createNestApplication();
app.useGlobalPipes(new ValidationPipe());
await app.init();
});
it(`should throw an error`, () => {
return request(app.getHttpServer())
.post('/graphql')
.send({
operationName: null,
variables: {},
query:
'mutation {\n addRecipe(newRecipeData: {title: "test", ingredients: []}) {\n id\n }\n}\n',
})
.expect(200, {
data: null,
errors: [
{
extensions: {
code: 'BAD_REQUEST',
originalError: {
error: 'Bad Request',
message: [
'description must be longer than or equal to 30 characters',
],
statusCode: 400,
},
},
locations: [
{
column: 3,
line: 2,
},
],
message: 'Bad Request Exception',
path: ['addRecipe'],
},
],
});
});
afterEach(async () => {
await app.close();
});
});

View File

@@ -1,21 +0,0 @@
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { join } from 'path';
import { RecipesModule } from './recipes/recipes.module';
@Module({
imports: [
RecipesModule,
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
includeStacktraceInErrorResponses: false,
installSubscriptionHandlers: true,
autoSchemaFile: join(
process.cwd(),
'integration/graphql-code-first/schema.gql',
),
}),
],
})
export class AppModule {}

View File

@@ -1,14 +0,0 @@
import { ArgsType, Field, Int } from '@nestjs/graphql';
import { Max, Min } from 'class-validator';
@ArgsType()
export class RecipesArgs {
@Field(type => Int)
@Min(0)
skip = 0;
@Field(type => Int)
@Min(1)
@Max(50)
take = 25;
}

View File

@@ -1,40 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"allowJs": true,
"outDir": "./dist",
"paths": {
"@nestjs/common": ["../../packages/common"],
"@nestjs/common/*": ["../../packages/common/*"],
"@nestjs/core": ["../../packages/core"],
"@nestjs/core/*": ["../../packages/core/*"],
"@nestjs/microservices": ["../../packages/microservices"],
"@nestjs/microservices/*": ["../../packages/microservices/*"],
"@nestjs/websockets": ["../../packages/websockets"],
"@nestjs/websockets/*": ["../../packages/websockets/*"],
"@nestjs/testing": ["../../packages/testing"],
"@nestjs/testing/*": ["../../packages/testing/*"],
"@nestjs/platform-express": ["../../packages/platform-express"],
"@nestjs/platform-express/*": ["../../packages/platform-express/*"],
"@nestjs/platform-socket.io": ["../../packages/platform-socket.io"],
"@nestjs/platform-socket.io/*": ["../../packages/platform-socket.io/*"],
"@nestjs/platform-ws": ["../../packages/platform-ws"],
"@nestjs/platform-ws/*": ["../../packages/platform-ws/*"]
}
},
"include": [
"src/**/*",
"e2e/**/*"
],
"exclude": [
"node_modules",
]
}

View File

@@ -1,8 +0,0 @@
import { Module } from '@nestjs/common';
import { ConfigService } from './config.service';
@Module({
providers: [ConfigService],
exports: [ConfigService],
})
export class ConfigModule {}

View File

@@ -1,8 +0,0 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();

View File

@@ -1,40 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"allowJs": true,
"outDir": "./dist",
"paths": {
"@nestjs/common": ["../../packages/common"],
"@nestjs/common/*": ["../../packages/common/*"],
"@nestjs/core": ["../../packages/core"],
"@nestjs/core/*": ["../../packages/core/*"],
"@nestjs/microservices": ["../../packages/microservices"],
"@nestjs/microservices/*": ["../../packages/microservices/*"],
"@nestjs/websockets": ["../../packages/websockets"],
"@nestjs/websockets/*": ["../../packages/websockets/*"],
"@nestjs/testing": ["../../packages/testing"],
"@nestjs/testing/*": ["../../packages/testing/*"],
"@nestjs/platform-express": ["../../packages/platform-express"],
"@nestjs/platform-express/*": ["../../packages/platform-express/*"],
"@nestjs/platform-socket.io": ["../../packages/platform-socket.io"],
"@nestjs/platform-socket.io/*": ["../../packages/platform-socket.io/*"],
"@nestjs/platform-ws": ["../../packages/platform-ws"],
"@nestjs/platform-ws/*": ["../../packages/platform-ws/*"]
}
},
"include": [
"src/**/*",
"e2e/**/*"
],
"exclude": [
"node_modules",
]
}

View File

@@ -1,4 +1,3 @@
import { ApolloDriver } from '@nestjs/apollo';
import { INestApplication } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { Test } from '@nestjs/testing';
@@ -16,7 +15,6 @@ describe('GraphQL request scoped', () => {
imports: [
CatsModule.enableRequestScope(),
GraphQLModule.forRoot({
driver: ApolloDriver,
typePaths: [join(__dirname, '..', 'src', '**', '*.graphql')],
}),
],

View File

@@ -1,14 +1,14 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
import { ApplicationModule } from '../src/app.module';
describe('GraphQL', () => {
let app: INestApplication;
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
imports: [ApplicationModule],
}).compile();
app = module.createNestApplication();

2100
integration/graphql/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,29 @@
{
"name": "nest-typescript-starter",
"version": "1.0.0",
"description": "Nest TypeScript starter repository",
"license": "MIT",
"scripts": {
"start": "ts-node src/main",
"prestart:prod": "tsc",
"start:prod": "node dist/main.js"
},
"dependencies": {
"@nestjs/common": "6.5.3",
"@nestjs/core": "6.5.3",
"@nestjs/graphql": "6.4.2",
"apollo-server-express": "2.8.1",
"graphql": "14.5.0",
"graphql-tools": "4.0.5",
"reflect-metadata": "0.1.13",
"rxjs": "6.5.2",
"subscriptions-transport-ws": "0.9.16",
"typescript": "3.5.3",
"ws": "7.1.2"
},
"devDependencies": {
"@types/node": "7.10.7",
"ts-node": "8.3.0",
"tslint": "5.19.0"
}
}

View File

@@ -1,4 +1,3 @@
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { join } from 'path';
@@ -7,11 +6,9 @@ import { CatsModule } from './cats/cats.module';
@Module({
imports: [
CatsModule,
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
includeStacktraceInErrorResponses: true,
GraphQLModule.forRoot({
typePaths: [join(__dirname, '**', '*.graphql')],
}),
],
})
export class AppModule {}
export class ApplicationModule {}

View File

@@ -1,11 +1,14 @@
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { Module } from '@nestjs/common';
import { GqlOptionsFactory, GraphQLModule } from '@nestjs/graphql';
import {
GqlModuleOptions,
GqlOptionsFactory,
GraphQLModule,
} from '@nestjs/graphql';
import { join } from 'path';
import { CatsModule } from './cats/cats.module';
class ConfigService implements GqlOptionsFactory {
createGqlOptions(): ApolloDriverConfig {
createGqlOptions(): GqlModuleOptions {
return {
typePaths: [join(__dirname, '**', '*.graphql')],
};
@@ -15,8 +18,7 @@ class ConfigService implements GqlOptionsFactory {
@Module({
imports: [
CatsModule,
GraphQLModule.forRootAsync<ApolloDriverConfig>({
driver: ApolloDriver,
GraphQLModule.forRootAsync({
useClass: ConfigService,
}),
],

View File

@@ -1,4 +1,3 @@
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { CatsModule } from './cats/cats.module';
@@ -8,8 +7,7 @@ import { ConfigService } from './config.service';
@Module({
imports: [
CatsModule,
GraphQLModule.forRootAsync<ApolloDriverConfig>({
driver: ApolloDriver,
GraphQLModule.forRootAsync({
imports: [ConfigModule],
useExisting: ConfigService,
}),

View File

@@ -1,4 +1,3 @@
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { join } from 'path';
@@ -7,8 +6,7 @@ import { CatsModule } from './cats/cats.module';
@Module({
imports: [
CatsModule,
GraphQLModule.forRootAsync<ApolloDriverConfig>({
driver: ApolloDriver,
GraphQLModule.forRootAsync({
useFactory: async () => ({
typePaths: [join(__dirname, '**', '*.graphql')],
}),

View File

@@ -14,7 +14,7 @@ export class CatsResolvers {
@Query()
@UseGuards(CatsGuard)
async getCats() {
return this.catsService.findAll();
return await this.catsService.findAll();
}
@Query('cat')
@@ -22,7 +22,7 @@ export class CatsResolvers {
@Args('id', ParseIntPipe)
id: number,
): Promise<Cat> {
return this.catsService.findOneById(id);
return await this.catsService.findOneById(id);
}
@Mutation('createCat')

View File

@@ -1,4 +1,4 @@
import { Scalar } from '@nestjs/graphql';
import { Scalar } from '@nestjs/graphql/dist/decorators/resolvers.decorators';
import { Kind } from 'graphql';
@Scalar('Date')

View File

@@ -1,8 +1,8 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ApplicationModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const app = await NestFactory.create(ApplicationModule);
await app.listen(3000);
}
bootstrap();

View File

@@ -1,17 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"target": "es6",
"sourceMap": true,
"allowJs": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true
},
"include": ["src/**/*"]
}
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}

View File

@@ -0,0 +1,54 @@
{
"defaultSeverity": "error",
"extends": [
"tslint:recommended"
],
"jsRules": {
"no-unused-expression": true
},
"rules": {
"eofline": false,
"quotemark": [
true,
"single"
],
"indent": false,
"ordered-imports": [
false
],
"max-line-length": [
150
],
"member-ordering": [
false
],
"curly": false,
"interface-name": [
false
],
"array-type": [
false
],
"member-access": [
false
],
"no-empty-interface": false,
"no-empty": false,
"arrow-parens": false,
"object-literal-sort-keys": false,
"no-unused-expression": false,
"max-classes-per-file": [
false
],
"variable-name": [
false
],
"one-line": [
false
],
"one-variable-per-declaration": [
false
]
},
"rulesDirectory": []
}

View File

@@ -1,134 +1,45 @@
import { HttpServer, HttpStatus, INestApplication } from '@nestjs/common';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { HttpStatus, INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { expect } from 'chai';
import * as request from 'supertest';
import { ErrorsController } from '../src/errors/errors.controller';
describe('Error messages', () => {
let server: HttpServer;
let server;
let app: INestApplication;
describe('Express', () => {
let app: INestApplication;
beforeEach(async () => {
const module = await Test.createTestingModule({
controllers: [ErrorsController],
}).compile();
beforeEach(async () => {
const module = await Test.createTestingModule({
controllers: [ErrorsController],
}).compile();
app = module.createNestApplication();
server = app.getHttpServer();
await app.init();
});
it(`/GET`, () => {
return request(server)
.get('/sync')
.expect(HttpStatus.BAD_REQUEST)
.expect({
statusCode: 400,
error: 'Bad Request',
message: 'Integration test',
});
});
it(`/GET (Promise/async)`, () => {
return request(server)
.get('/async')
.expect(HttpStatus.BAD_REQUEST)
.expect({
statusCode: 400,
error: 'Bad Request',
message: 'Integration test',
});
});
it(`/GET (InternalServerError despite custom content-type)`, async () => {
return request(server)
.get('/unexpected-error')
.expect(HttpStatus.INTERNAL_SERVER_ERROR)
.expect({
statusCode: 500,
message: 'Internal server error',
});
});
afterEach(async () => {
await app.close();
});
app = module.createNestApplication();
server = app.getHttpServer();
await app.init();
});
describe('Fastify', () => {
let app: NestFastifyApplication;
beforeEach(async () => {
const module = await Test.createTestingModule({
controllers: [ErrorsController],
}).compile();
it(`/GET`, () => {
return request(server)
.get('/sync')
.expect(HttpStatus.BAD_REQUEST)
.expect({
statusCode: 400,
error: 'Bad Request',
message: 'Integration test',
});
});
app = module.createNestApplication<NestFastifyApplication>(
new FastifyAdapter(),
);
server = app.getHttpServer();
await app.init();
});
it(`/GET (Promise/async)`, () => {
return request(server)
.get('/async')
.expect(HttpStatus.BAD_REQUEST)
.expect({
statusCode: 400,
error: 'Bad Request',
message: 'Integration test',
});
});
it(`/GET`, async () => {
return app
.inject({
method: 'GET',
url: '/sync',
})
.then(({ payload, statusCode }) => {
expect(statusCode).to.equal(HttpStatus.BAD_REQUEST);
expect(payload).to.equal(
JSON.stringify({
statusCode: 400,
error: 'Bad Request',
message: 'Integration test',
}),
);
});
});
it(`/GET (Promise/async)`, async () => {
return app
.inject({
method: 'GET',
url: '/sync',
})
.then(({ payload, statusCode }) => {
expect(statusCode).to.equal(HttpStatus.BAD_REQUEST);
expect(payload).to.equal(
JSON.stringify({
statusCode: 400,
error: 'Bad Request',
message: 'Integration test',
}),
);
});
});
it(`/GET (InternalServerError despite custom content-type)`, async () => {
return app
.inject({
method: 'GET',
url: '/unexpected-error',
})
.then(({ payload, statusCode }) => {
expect(statusCode).to.equal(HttpStatus.INTERNAL_SERVER_ERROR);
expect(payload).to.equal(
JSON.stringify({
statusCode: 500,
message: 'Internal server error',
}),
);
});
});
afterEach(async () => {
await app.close();
});
afterEach(async () => {
await app.close();
});
});

View File

@@ -1,132 +0,0 @@
import {
Controller,
Get,
INestApplication,
MiddlewareConsumer,
Module,
Post,
RequestMethod,
} from '@nestjs/common';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
const RETURN_VALUE = 'test';
const MIDDLEWARE_VALUE = 'middleware';
@Controller()
class TestController {
@Get('test')
test() {
return RETURN_VALUE;
}
@Get('test/test')
testTest() {
return RETURN_VALUE;
}
@Get('test2')
test2() {
return RETURN_VALUE;
}
@Get('middleware')
middleware() {
return RETURN_VALUE;
}
@Post('middleware')
noMiddleware() {
return RETURN_VALUE;
}
@Get('wildcard/overview')
testOverview() {
return RETURN_VALUE;
}
@Get('overview/:id')
overviewById() {
return RETURN_VALUE;
}
}
@Module({
imports: [AppModule],
controllers: [TestController],
})
class TestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply((req, res, next) => res.end(MIDDLEWARE_VALUE))
.exclude('test', 'overview/:id', 'wildcard/(.*)', {
path: 'middleware',
method: RequestMethod.POST,
})
.forRoutes('*');
}
}
describe('Exclude middleware (fastify)', () => {
let app: INestApplication;
beforeEach(async () => {
app = (
await Test.createTestingModule({
imports: [TestModule],
}).compile()
).createNestApplication<NestFastifyApplication>(new FastifyAdapter());
await app.init();
await app.getHttpAdapter().getInstance().ready();
});
it(`should exclude "/test" endpoint`, () => {
return request(app.getHttpServer()).get('/test').expect(200, RETURN_VALUE);
});
it(`should not exclude "/test/test" endpoint`, () => {
return request(app.getHttpServer())
.get('/test/test')
.expect(200, MIDDLEWARE_VALUE);
});
it(`should not exclude "/test2" endpoint`, () => {
return request(app.getHttpServer())
.get('/test2')
.expect(200, MIDDLEWARE_VALUE);
});
it(`should run middleware for "/middleware" endpoint`, () => {
return request(app.getHttpServer())
.get('/middleware')
.expect(200, MIDDLEWARE_VALUE);
});
it(`should exclude POST "/middleware" endpoint`, () => {
return request(app.getHttpServer())
.post('/middleware')
.expect(201, RETURN_VALUE);
});
it(`should exclude "/overview/:id" endpoint (by param)`, () => {
return request(app.getHttpServer())
.get('/overview/1')
.expect(200, RETURN_VALUE);
});
it(`should exclude "/wildcard/overview" endpoint (by wildcard)`, () => {
return request(app.getHttpServer())
.get('/wildcard/overview')
.expect(200, RETURN_VALUE);
});
afterEach(async () => {
await app.close();
});
});

View File

@@ -1,116 +0,0 @@
import {
Controller,
Get,
INestApplication,
MiddlewareConsumer,
Module,
Post,
RequestMethod,
} from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
const RETURN_VALUE = 'test';
const MIDDLEWARE_VALUE = 'middleware';
@Controller()
class TestController {
@Get('test')
test() {
return RETURN_VALUE;
}
@Get('test2')
test2() {
return RETURN_VALUE;
}
@Get('middleware')
middleware() {
return RETURN_VALUE;
}
@Post('middleware')
noMiddleware() {
return RETURN_VALUE;
}
@Get('wildcard/overview')
testOverview() {
return RETURN_VALUE;
}
@Get('overview/:id')
overviewById() {
return RETURN_VALUE;
}
}
@Module({
imports: [AppModule],
controllers: [TestController],
})
class TestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply((req, res, next) => res.send(MIDDLEWARE_VALUE))
.exclude('test', 'overview/:id', 'wildcard/(.*)', {
path: 'middleware',
method: RequestMethod.POST,
})
.forRoutes('*');
}
}
describe('Exclude middleware', () => {
let app: INestApplication;
beforeEach(async () => {
app = (
await Test.createTestingModule({
imports: [TestModule],
}).compile()
).createNestApplication();
await app.init();
});
it(`should exclude "/test" endpoint`, () => {
return request(app.getHttpServer()).get('/test').expect(200, RETURN_VALUE);
});
it(`should not exclude "/test2" endpoint`, () => {
return request(app.getHttpServer())
.get('/test2')
.expect(200, MIDDLEWARE_VALUE);
});
it(`should run middleware for "/middleware" endpoint`, () => {
return request(app.getHttpServer())
.get('/middleware')
.expect(200, MIDDLEWARE_VALUE);
});
it(`should exclude POST "/middleware" endpoint`, () => {
return request(app.getHttpServer())
.post('/middleware')
.expect(201, RETURN_VALUE);
});
it(`should exclude "/overview/:id" endpoint (by param)`, () => {
return request(app.getHttpServer())
.get('/overview/1')
.expect(200, RETURN_VALUE);
});
it(`should exclude "/wildcard/overview" endpoint (by wildcard)`, () => {
return request(app.getHttpServer())
.get('/wildcard/overview')
.expect(200, RETURN_VALUE);
});
afterEach(async () => {
await app.close();
});
});

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