A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications on top of TypeScript & JavaScript (ES6, ES7, ES8) ๐Ÿš€

Overview

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads CircleCI Coverage Discord Backers on Open Collective Sponsors on Open Collective Support us

Description

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses modern JavaScript, is built with TypeScript (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).

Under the hood, Nest makes use of Express, but also, provides compatibility with a wide range of other libraries, like e.g. Fastify, allowing for easy use of the myriad third-party plugins which are available.

Philosophy

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 Angular, React and Vue 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.

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.

Getting started

Questions

For questions and support please use the official Discord channel. The issue list of this repo is exclusively for bug reports and feature requests.

Issues

Please make sure to read the Issue Reporting Checklist 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.

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.

Principal Sponsors

Gold Sponsors

Silver Sponsors

Sponsors

Backers

Stay in touch

License

Nest is MIT licensed.

Comments
  • feat(microservice) Kafka Support #2361

    feat(microservice) Kafka Support #2361

    PR Checklist

    Please check if your PR fulfills the following requirements:

    • [x] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
    • [x] Tests for the changes have been added (for bug fixes / features)
    • [ ] Docs have been added / updated (for bug fixes / features)

    PR Type

    What kind of change does this PR introduce?

    [ ] Bugfix
    [x] 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?

    https://github.com/nestjs/nest/issues/2361

    Issue Number: #2361

    What is the new behavior?

    Does this PR introduce a breaking change?

    [ ] Yes
    [x] No
    

    Other information

    type: feature :tada: scope: microservices status: wip โšก๏ธ 
    opened by mkaufmaner 67
  • refactor(#1640): support multiple packages (breaking changes)

    refactor(#1640): support multiple packages (breaking changes)

    PR Checklist

    Please check if your PR fulfills the following requirements:

    • [x] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
    • [x] Tests for the changes have been added (for bug fixes / features)
    • [ ] Docs have been added / updated (for bug fixes / features)

    PR Type

    What kind of change does this PR introduce?

    [ ] Bugfix
    [x] 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?

    Issue Number: #1640

    What is the new behavior?

    const grpcServerOptions: GrpcOptions = {
      transport: Transport.GRPC,
      options: {
        url: 'localhost:5577',
        packages: ['product', 'order'],      // <--- this line
        protoPath: join(__dirname, './proto/payment.proto'),
        loader: {
          includeDirs: [
            join(__dirname, 'proto'),
          ],
        }
      },
    } 
    

    Does this PR introduce a breaking change?

    [x] Yes
    [ ] No
    

    Other information

    scope: microservices 
    opened by zry656565 65
  • Unable to run tests because Nest can't resolve dependencies of a service

    Unable to run tests because Nest can't resolve dependencies of a service

    I'm submitting a...

    
    [ ] Regression 
    [ ] Bug report
    [ ] Feature request
    [x] Documentation issue or request
    [ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
    

    Current behavior

    I have followed the unit test example but I am unable to get my very simple test to run (it's literally just testing if true === true) but it won't work because I'm met with this error

    Nest can't resolve dependencies of the RoleService (?). Please verify whether [0] argument is available in the current context.

    Minimal reproduction of the problem with instructions

    You can find the repo at https://bitbucket.org/mogusbi/breeze-bb/

    After cloning, run npm run api:test

    // role.controller.spec.ts
    import {Test} from '@nestjs/testing';
    import {TestingModule} from '@nestjs/testing/testing-module';
    import {RoleController} from './role.controller';
    import {RoleService} from './role.service';
    
    describe('Role controller', () => {
      let controller: RoleController;
      let service: RoleService;
    
      beforeEach(async () => {
        const mod: TestingModule = await Test
          .createTestingModule({
            components: [
              RoleService
            ],
            controllers: [
              RoleController
            ]
          })
          .compile();
    
        controller = mod.get<RoleController>(RoleController);
        service = mod.get<RoleService>(RoleService);
      });
    
      it('should be true', () => {
        expect(true).toBe(true);
      });
    });
    
    // role.controller.ts
    import {Controller} from '@nestjs/common';
    import {RoleService} from './role.service';
    
    @Controller('role')
    export class RoleController {
      constructor (
        private readonly roleService: RoleService
      ) {}
    
      ...
    }
    
    // role.service.ts
    import {InjectModel} from '@nestjs/mongoose';
    import {PaginateModel} from 'mongoose';
    import {IRole} from './role.interface';
    import {RoleSchema} from './role.schema';
    
    @Component()
    export class RoleService {
      constructor (
        @InjectModel(RoleSchema) private readonly model: PaginateModel<IRole>
      ) {}
    
      ...
    }
    

    Environment

    
    - Node version: 8.2.1
    - Platform:  Mac OS 10.13.2
    
    โ”œโ”€โ”€ @nestjs/[email protected]
    โ”œโ”€โ”€ @nestjs/[email protected]
    โ”œโ”€โ”€ @nestjs/[email protected]
    โ”œโ”€โ”€ @nestjs/[email protected]
    โ”œโ”€โ”€ @nestjs/[email protected]
    โ”œโ”€โ”€ @types/[email protected]
    โ”œโ”€โ”€ @types/[email protected]
    โ”œโ”€โ”€ @types/[email protected]
    โ”œโ”€โ”€ @types/[email protected]
    โ”œโ”€โ”€ @types/[email protected]
    โ”œโ”€โ”€ @types/[email protected]
    โ”œโ”€โ”€ @types/[email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ”œโ”€โ”€ [email protected]
    โ””โ”€โ”€ [email protected]
    
    type: question ๐Ÿ™Œ type: docs :page_facing_up: 
    opened by mogusbi 53
  • use yarn workspace to build packages

    use yarn workspace to build packages

    PR Checklist

    Please check if your PR fulfills the following requirements:

    • [x] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
    • [x] Tests for the changes have been added (for bug fixes / features)
    • [x] Docs have been added / updated (for bug fixes / features)

    PR Type

    What kind of change does this PR introduce?

    [ ] Bugfix
    [ ] Feature
    [ ] Code style update (formatting, local variables)
    [ ] Refactoring (no functional changes, no api changes)
    [x] Build related changes
    [ ] CI related changes
    [ ] Other... Please describe:
    

    What is the current behavior?

    Issue Number: N/A

    What is the new behavior?

    I rebased my original pull request in https://github.com/nestjs/nest/pull/954 and send this new pull request, changes includes:

    1. use yarn workspace to build packages
    2. deleted the bundle directory to exclude the compiled files from the repo
    3. included sample directory into workspace to use the latest nest library in sample

    how to test this pr

    1. clone this repo. git clone https://github.com/xcaptain/nest
    2. cd nest
    3. git checkout feature/workspace
    4. yarn install this will install all the dependencies in packages and sample
    5. yarn bootstrap to bootstrap lerna
    6. after made any changes run yarn prepare to re-generate lib in each packages
    7. yarn test to run all the tests or ../../node_modules/mocha/bin/mocha --require ts-node/register test/**/*.spec.ts in each packages
    8. yarn pub to publish the packages, this command will publish the source code and compiled code

    how to run the sample

    1. cd sample/01-cats-app/
    2. yarn start
    3. curl -i 'localhost:3000/cats/

    what to do in the future

    • [ ] put all the source code into a src directory in each packages and compiled into lib dir
    • [ ] delete unnessary dependencies in sample dir
    • [ ] try typescript 3 project reference feature

    Does this PR introduce a breaking change?

    [ ] Yes
    [x] No
    

    Other information

    type: build 
    opened by xcaptain 52
  • Dependency injection with class-validator

    Dependency injection with class-validator

    I'm submitting a...

    
    [ ] Regression 
    [ ] Bug report
    [ ] Feature request
    [x ] Documentation issue or request
    [ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
    

    Current behavior

    As mentioned in the documention NestJS is supposed to works well very with class validator, however i'm not successful trying to implement a custom validation class ( https://github.com/typestack/class-validator#custom-validation-classes ) or decorator. This usecase is more than usefull to implement complex validation logic that require injecting services As its a pretty standart usecase, i guess that there is a way to do it, but i'm not able to find it! could be a great addition to the online documentation imo !

    Expected behavior

    I've tried to add my Validator class as a component but not working. In the class-validator documentation they mentioned that we can register a DI, is this doable with Nest ?

    Minimal reproduction of the problem with instructions

    @Controller('cars')
    export class CarController {
    
        @Get()
        public test(@Res() res) {
            const dto = new CarInsertDTO();
            dto.brand = 'toyota';
    
            validate(dto).then(errs => {
                if (errs && errs.length > 0) {
                    throw new BadRequestException(errs);
                }
    
                res.send(200);
            });
        }
    }
    
    export class CarInsertDTO {
        @IsString()
        public name: string;
    
        @Validate(BrandValidator, { message: 'Invalid brand'})
        public readonly strategy;
    }
    
    
    @ValidatorConstraint()
    export class BrandValidator implements ValidatorConstraintInterface {
        constructor(private readonly brandService: BrandService) {}
    
        validate(brandName: any, args: ValidationArguments) {
            // can be a http service , database service or whatever
            const brands: string[] = this.brandService.all();
    
            return brands.indexOf(brandName) >= 0;
        }
    }
    

    Should lead to something like

    [Nest] 1736 - 2018-3-26 12:16:38 [ExceptionsHandler] Cannot read property 'all' of undefined TypeError: Cannot read property 'all' of undefined

    type: question ๐Ÿ™Œ 
    opened by fmeynard 45
  • Future of the framework, contributions, evangelism

    Future of the framework, contributions, evangelism

    @kamilmysliwiec

    First of all I'd like to say I really like the idea and your work so far, secondly: what are you plans for the future of the project? Here are some questions I'd love to hear your answers to.

    1. Do you plan to move it to it's own GitHub organization (eg. nest/nest)?
    2. Do you intend to create a website (GitHub Pages?)?
    3. How do you want to approach contributions?
    4. Is there any roadmap?
    5. Are you going to make some future milestones that community could help you achieve?
    6. What are your plans for making the framework more popular (and thus attract more contributors)?

    Thanks for the answers.

    type: discussion ๐Ÿ”ฅ 
    opened by galkowskit 45
  • Channel for Discussions e.g. Discord

    Channel for Discussions e.g. Discord

    Question

    Is there an open channel for more "informal" discussions related to Nest?

    Why

    I want to contribute more I would like to chat with the creators a little bit more, or share things I've created with Nest etc. Issues are often not the best place to start these kinds of discussions. So I suggest something like Discord / Gitter / Slack / Subreddit.

    I suggest a platform which supports different channels like Discord or Slack, so contributors / core developers could chat in a dedicated channel and would not get polluted with beginner questions.

    Poll

    Use a reaction on this issue to vote.

    :+1: Discord :-1: Stay with Gitter :laughing: Slack :tada: Spectrum :heart: Telegram :confused: Other (comment)

    type: discussion ๐Ÿ”ฅ 
    opened by BrunnerLivio 44
  • Proper way to initialize config

    Proper way to initialize config

    I'm submitting a...

    [ ] Regression [ ] Bug report [ ] Feature request [x] Documentation issue or request [ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

    Current behavior

    There is nothing but a short snippet about a "configServiceProvider" in the documentation:

    const configServiceProvider = {
      provide: ConfigService,
      useClass: DevelopmentConfigService,
    };
    
    @Module({
      components: [configServiceProvider],
    })
    

    Expected behavior

    One article describing how to properly create a ConfigService provider which loads variables from the .env file, including validation (for example: is port actually a number between 1 and 65535?) and usage in other components.

    It could easily be added to one of the examples showing how to pass database credentials for example.

    type: docs :page_facing_up: 
    opened by kentorio 43
  • How to access current http context inside component method

    How to access current http context inside component method

    Hi,

    How to access current http context inside component method? As an example i would like to access current session user inside "typeorm" EventSubscriber class to automatically set user who inserted/update/deleted record.

    Thanks for nice framework!

    type: help wanted :slightly_smiling_face: 
    opened by darioxtx 43
  • Global prefix for a module / route tree

    Global prefix for a module / route tree

    Hi,

    there is an older issue, which got implemented: https://github.com/nestjs/nest/issues/40 - allowing to setGlobalPrefix('api') on the app instance.

    This is a very neat feature and since I'm looking to create some sort of a "route tree", it would be great to set some "route extending strategy".

    Say I want to create a route tree like this: -> api (from app.setGlobalPrefix) --> /users (UsersModule with prefix 'users' for all of it's 'children' modules and controllers) ---> /posts (PostsModule with prefix 'posts' for all of it's 'children' modules and controllers) ----> /comments (Now I could declare a CommentsController with route 'comments' and this controller's route would be composed from all of the ancestors above, in this case: 'api/users/posts/comments' ----> /upvotes (this one would then be 'api/users/posts/upvotes')

    that means I'd like to somehow set the 'module route prefix' for all of it's children's modules & controllers.

    If there's already a way to achieve this, please point me in the right direction, otherwise it would be pretty nice to have this.

    Thanks

    type: discussion ๐Ÿ”ฅ 
    opened by lukgri 41
  • Extracting Express in a seperate module

    Extracting Express in a seperate module

    Big fan of this this framework, good work! I created a REST API with it and it works like a charm.

    My use case is an application, which has nothing to do with an webserver. Its a standalone application. Now it would be really nice to still use decorators like @Component or @Module etc. If I would want to have these features, I have to use @nestjs/core as dependency in my application. Now I have the dependency express, even though my application does not even need it.

    It would be nice to split the functionality of all the webserver-stuff in a seperate module. For me atleast, that would fit the pattern. Want NestJS? Install @nestjs/core. Need a webserver? Install @nestjs/web. Need websockets? Install @nestjs/websocket Need an orm? Install @nestjs/typeorm

    Are there any plans to extract express in an seperate module?

    type: discussion ๐Ÿ”ฅ type: future plan ๐Ÿท 
    opened by BrunnerLivio 40
  • chore(deps-dev): bump mongoose from 6.8.2 to 6.8.3

    chore(deps-dev): bump mongoose from 6.8.2 to 6.8.3

    Bumps mongoose from 6.8.2 to 6.8.3.

    Release notes

    Sourced from mongoose's releases.

    6.8.3 / 2023-01-06

    • perf: improve performance of assignRawDocsToIdStructure for faster populate on large docs #12867 Uzlopak
    • fix(model): ensure consistent ordering of validation errors in insertMany() with ordered: false and rawResult: true #12866
    • fix: avoid passing final callback to pre hook, because calling the callback can mess up hook execution #12836
    • fix(types): avoid inferring timestamps if methods, virtuals, or statics set #12871
    • fix(types): correctly infer string enums on const arrays #12870 JavaScriptBach
    • fix(types): allow virtuals to be invoked in the definition of other virtuals #12874 sffc
    • fix(types): add type def for Aggregate#model without arguments #12864 hasezoey
    • docs(discriminators): add section about changing discriminator key #12861
    • docs(typescript): explain that virtuals inferred from schema only show up on Model, not raw document type #12860 #12684
    Changelog

    Sourced from mongoose's changelog.

    6.8.3 / 2023-01-06

    • perf: improve performance of assignRawDocsToIdStructure for faster populate on large docs #12867 Uzlopak
    • fix(model): ensure consistent ordering of validation errors in insertMany() with ordered: false and rawResult: true #12866
    • fix: avoid passing final callback to pre hook, because calling the callback can mess up hook execution #12836
    • fix(types): avoid inferring timestamps if methods, virtuals, or statics set #12871
    • fix(types): correctly infer string enums on const arrays #12870 JavaScriptBach
    • fix(types): allow virtuals to be invoked in the definition of other virtuals #12874 sffc
    • fix(types): add type def for Aggregate#model without arguments #12864 hasezoey
    • docs(discriminators): add section about changing discriminator key #12861
    • docs(typescript): explain that virtuals inferred from schema only show up on Model, not raw document type #12860 #12684
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies javascript 
    opened by dependabot[bot] 1
  • chore(deps-dev): bump prettier from 2.8.1 to 2.8.2

    chore(deps-dev): bump prettier from 2.8.1 to 2.8.2

    Bumps prettier from 2.8.1 to 2.8.2.

    Release notes

    Sourced from prettier's releases.

    2.8.2

    ๐Ÿ”— Changelog

    Changelog

    Sourced from prettier's changelog.

    2.8.2

    diff

    Don't lowercase link references (#13155 by @โ€‹DerekNonGeneric & @โ€‹fisker)

    <!-- Input -->
    We now don't strictly follow the release notes format suggested by [Keep a Changelog].
    

    <!-- Prettier 2.8.1 --> We now don't strictly follow the release notes format suggested by Keep a Changelog.

    <!-- ^^^^^^^^^^^^^^^^^^ lowercased -->

    <!-- Prettier 2.8.2 --> <Same as input>

    Preserve self-closing tags (#13691 by @โ€‹dcyriller)

    {{! Input }}
    <div />
    <div></div>
    <custom-component />
    <custom-component></custom-component>
    <i />
    <i></i>
    <Component />
    <Component></Component>
    

    {{! Prettier 2.8.1 }} <div></div> <div></div> <custom-component></custom-component> <custom-component></custom-component> <i></i> <i></i> <Component /> <Component />

    {{! Prettier 2.8.2 }} </tr></table>

    ... (truncated)

    Commits
    • ac88438 Release 2.8.2
    • aaf9190 Fix comments after directive (#14081)
    • 9e09a78 Stop inserting space in LESS property access (#14103)
    • 0c5d4f3 Fix removing commas from function arguments in maps (#14089)
    • b77d912 ember / glimmer: Preserve self-closing tags (#13691)
    • cf36209 Handlebars: Add tests for {{! prettier-ignore}} (#13693)
    • f8e1ad8 Add parens to head of ExpressionStatement instead of whole statement (#14077)
    • 8034bad Build(deps): Bump json5 from 2.2.0 to 2.2.3 in /scripts/release (#14104)
    • 31d4010 Build(deps): Bump json5 from 2.2.1 to 2.2.3 in /website (#14101)
    • 41cee06 Do not change case of property name if inside a variable declaration in LESS ...
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies javascript 
    opened by dependabot[bot] 1
  • chore(deps): bump ws from 8.11.0 to 8.12.0

    chore(deps): bump ws from 8.11.0 to 8.12.0

    Bumps ws from 8.11.0 to 8.12.0.

    Release notes

    Sourced from ws's releases.

    8.12.0

    Features

    • Added support for utf-8-validate@6 (ff63bba3).

    Other notable changes

    • buffer.isUtf8() is now used instead of utf-8-validate if available (42d79f60).
    Commits
    • a3214d3 [dist] 8.12.0
    • 42d79f6 [minor] Use buffer.isUtf8() if possible
    • ff63bba [pkg] Update utf-8-validate to version 6.0.0
    • d412358 [minor] Fix nits
    • 2dc2812 [minor] Make sendAfterClose() call the callback in the next tick
    • fb1dfd2 [doc] Fix badge URL
    • 83c72cf [perf] Make toBuffer() use FastBuffer
    • 1b057f9 [minor] Fix nit
    • e6a32f8 [perf] Use FastBuffer instead of Buffer#subarray()
    • 9e0fd77 [minor] Use Buffer#subarray() instead of Buffer#slice()
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies javascript 
    opened by dependabot[bot] 1
  • There is no matching event handler defined in the remote service

    There is no matching event handler defined in the remote service

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Current behavior

    Emitting an event (via RabbitMQ transport) fails every second time with the error: There is no matching event handler defined in the remote service. Event pattern: test_msg

    Minimum reproduction code

    https://github.com/ddimitrioglo/nestjs-reproduction-example

    Steps to reproduce

    1. Install dependencies in both (first & second microservices): npm install
    2. Start both microservices: npm run start:dev
    3. Trigger event emission: http://localhost:3001/trigger

    Expected behavior

    Receive every event

    Package

    • [ ] I don't know. Or some 3rd-party package
    • [ ] @nestjs/common
    • [ ] @nestjs/core
    • [X] @nestjs/microservices
    • [ ] @nestjs/platform-express
    • [ ] @nestjs/platform-fastify
    • [ ] @nestjs/platform-socket.io
    • [ ] @nestjs/platform-ws
    • [ ] @nestjs/testing
    • [ ] @nestjs/websockets
    • [ ] Other (see below)

    Other package

    No response

    NestJS version

    9.2.1

    Packages versions

    [System Information]
    OS Version     : macOS
    NodeJS Version : v14.17.5
    NPM Version    : 6.14.14 
    
    [Nest CLI]
    Nest CLI Version : 9.1.8 
    
    [Nest Platform Information]
    platform-express version : 9.2.1
    microservices version    : 9.2.1
    schematics version       : 9.0.4
    testing version          : 9.2.1
    common version           : 9.2.1
    core version             : 9.2.1
    cli version              : 9.1.8
    

    Node.js version

    14.17.5

    In which operating systems have you tested?

    • [X] macOS
    • [ ] Windows
    • [ ] Linux

    Other

    No response

    needs triage 
    opened by ddimitrioglo 0
  • perf(common): faster random string generator

    perf(common): faster random string generator

    PR Checklist

    Please check if your PR fulfills the following requirements:

    • [x] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
    • [ ] Tests for the changes have been added (for bug fixes / features)
    • [ ] Docs have been added / updated (for bug fixes / features)

    PR Type

    What kind of change does this PR introduce?

    • [ ] Bugfix
    • [ ] Feature
    • [ ] Code style update (formatting, local variables)
    • [x] Refactoring (no functional changes, no api changes)
    • [ ] Build related changes
    • [ ] CI related changes
    • [ ] Other... Please describe:

    What is the current behavior?

    The method randomStringGenerator is implemented with uuid package, which is slow when we compare with other package like uid:

    uuid x 4,724,786 ops/sec ยฑ2.35% (81 runs sampled)
    nanoid x 2,880,683 ops/sec ยฑ2.16% (79 runs sampled)
    uid x 37,413,066 ops/sec ยฑ1.91% (85 runs sampled)
    Fastest is uid
    

    Benchmark

    This method is also used inside instance-wrapper.ts, which is instantiated a lot during the initialization of NestJS, above the profiling information:

     [Shared libraries]:
       ticks  total  nonlib   name
      35505   66.5%          /home/h4ad/.asdf/installs/nodejs/12.22.12/bin/node
        725    1.4%          /usr/lib/x86_64-linux-gnu/libc-2.31.so
         18    0.0%          /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28
          3    0.0%          [vdso]
    
    [JavaScript]:
       ticks  total  nonlib   name
        435    0.8%    2.5%  LazyCompile: *OrdinaryGetMetadata /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/reflect-metadata/Reflect.js:600:37
        316    0.6%    1.8%  LazyCompile: *getAllFilteredMethodNames /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/@nestjs/core/metadata-scanner.js:14:31
        307    0.6%    1.8%  LazyCompile: *reflectKeyMetadata /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/@nestjs/core/scanner.js:150:23
        264    0.5%    1.5%  LazyCompile: *reflectDynamicMetadata /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/@nestjs/core/scanner.js:117:27
        251    0.5%    1.5%  LazyCompile: *next /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/iterare/lib/iterate.js:20:9
        217    0.4%    1.3%  LazyCompile: *_object /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/object-hash/index.js:192:22
        213    0.4%    1.2%  LazyCompile: *loadInstance /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/@nestjs/core/injector/injector.js:30:23
        177    0.3%    1.0%  LazyCompile: *_string /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/object-hash/index.js:304:22
        175    0.3%    1.0%  LazyCompile: *__rest /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/tslib/tslib.js:85:23
        174    0.3%    1.0%  LazyCompile: *unsafeStringify /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/uuid/dist/stringify.js:23:25
    

    Source

    The last call unsafeStringify is the problem.

    Issue Number: N/A

    What is the new behavior?

    I added a new package called uid based on the previous benchmark to generate faster random strings.

    Now, when we see the profiling information:

    [Shared libraries]:
       ticks  total  nonlib   name
      32573   66.1%          /home/h4ad/.asdf/installs/nodejs/12.22.12/bin/node
        696    1.4%          /usr/lib/x86_64-linux-gnu/libc-2.31.so
          6    0.0%          /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28
          2    0.0%          [vdso]
    
     [JavaScript]:
       ticks  total  nonlib   name
        468    1.0%    2.9%  LazyCompile: *OrdinaryGetMetadata /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/reflect-metadata/Reflect.js:600:37
        320    0.6%    2.0%  LazyCompile: *getAllFilteredMethodNames /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/@nestjs/core/metadata-scanner.js:14:31
        274    0.6%    1.7%  LazyCompile: *reflectKeyMetadata /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/@nestjs/core/scanner.js:150:23
        249    0.5%    1.6%  LazyCompile: *next /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/iterare/lib/iterate.js:20:9
        237    0.5%    1.5%  LazyCompile: *applyDefaults /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/object-hash/index.js:61:23
        205    0.4%    1.3%  LazyCompile: *write /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/object-hash/index.js:169:23
        192    0.4%    1.2%  LazyCompile: *loadInstance /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/@nestjs/core/injector/injector.js:30:23
        186    0.4%    1.2%  LazyCompile: *reflectDynamicMetadata /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/@nestjs/core/scanner.js:117:27
        176    0.4%    1.1%  LazyCompile: *_string /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/object-hash/index.js:304:22
        165    0.3%    1.0%  LazyCompile: *__rest /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/tslib/tslib.js:85:23
    

    Source

    We have almost 3k ticks less than the previous version using uuid, when we search for uid, we found this line:

    23    0.0%    0.1%  LazyCompile: *uid /home/h4ad/Projects/opensource/performance-analysis/test-performance-nestjs/node_modules/uid/dist/index.js:4:13  
    

    Much faster compared to 174 ticks from the previous package.

    From my tests, creating 10,000 times an API with 20 modules, I went from 7.1213ms to 6.451ms to initialize NestJS. This value can fluctuate depending on the machine and how many times you run but my baseline of improvement was the profiler information.

    Benchmark.

    Does this PR introduce a breaking change?

    • [ ] Yes
    • [x] No

    Other information

    opened by H4ad 0
  • perf(common): faster logs by caching intl.datetimeformat

    perf(common): faster logs by caching intl.datetimeformat

    PR Checklist

    Please check if your PR fulfills the following requirements:

    • [x] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
    • [ ] Tests for the changes have been added (for bug fixes / features)
    • [ ] Docs have been added / updated (for bug fixes / features)

    PR Type

    What kind of change does this PR introduce?

    • [ ] Bugfix
    • [ ] Feature
    • [ ] Code style update (formatting, local variables)
    • [x] Refactoring (no functional changes, no api changes)
    • [ ] Build related changes
    • [ ] CI related changes
    • [ ] Other... Please describe:

    What is the current behavior?

    This is the profiler information when we call #log method 10.000 times:

    [Bottom up (heavy) profile]:
      Note: percentage shows a share of a particular caller in the total
      amount of its parent calls.
      Callers occupying less than 1.0% are not shown.
    
       ticks parent  name
        958   56.8%  /home/h4ad/.asdf/installs/nodejs/12.22.12/bin/node
        763   79.6%    v8::internal::Builtin_DatePrototypeToLocaleString(int, unsigned long*, v8::internal::Isolate*)
        560   73.4%      LazyCompile: *getTimestamp /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/console-logger.service.js:104:17
        510   91.1%        LazyCompile: *log /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/console-logger.service.js:28:8
        510  100.0%          LazyCompile: *log /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/logger.service.js:36:8
        510  100.0%            LazyCompile: ~descriptor.value /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/logger.service.js:155:33
         50    8.9%        LazyCompile: *printMessages /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/console-logger.service.js:115:18
         50  100.0%          LazyCompile: ~log /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/console-logger.service.js:28:8
         50  100.0%            LazyCompile: *log /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/logger.service.js:36:8
        203   26.6%      LazyCompile: ~getTimestamp /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/console-logger.service.js:104:17
        179   88.2%        LazyCompile: ~formatMessage /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/console-logger.service.js:131:18
        179  100.0%          LazyCompile: ~<anonymous> /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/console-logger.service.js:116:26
        179  100.0%            /home/h4ad/.asdf/installs/nodejs/12.22.12/bin/node
         24   11.8%        LazyCompile: *printMessages /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/console-logger.service.js:115:18
         24  100.0%          LazyCompile: ~log /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/console-logger.service.js:28:8
         24  100.0%            LazyCompile: ~log /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/node_modules/@nestjs/common/services/logger.service.js:36:8
    

    Source

    As you can see, getTimestamp consumes most of the execution time, which doesn't make sense, I did some CPU profiling and I found this:

    image

    normal_logger_nodejs12.cpuprofile.zip

    The #getTimestamp method took 1ms, in another test that I did, this function

    When we run again on nodejs16 or nodejs19:

    image

    The #getTimestamp method took 13ms (I think I found a regression on NodeJS).

    normal_logger_nodejs16.cpuprofile.zip normal_logger_nodejs19.cpuprofile.zip

    Also, decorators like WrapBuffer tends to not be optimized by V8, so this could be another point of optimization.

    Issue Number: N/A

    What is the new behavior?

    So, to solve the issue with #getTimestamp, I started using Intl.DateTimeFormat API, and for the decorator WrapBuffer, I just refactor to use a function.

    The final profiler information became:

    [Bottom up (heavy) profile]:
      Note: percentage shows a share of a particular caller in the total
      amount of its parent calls.
      Callers occupying less than 1.0% are not shown.
    
       ticks parent  name
        207   45.3%  /home/h4ad/.asdf/installs/nodejs/12.22.12/bin/node
         61   29.5%    /home/h4ad/.asdf/installs/nodejs/12.22.12/bin/node
          6    9.8%      /home/h4ad/.asdf/installs/nodejs/12.22.12/bin/node
          2   33.3%        LazyCompile: ~readPackage internal/modules/cjs/loader.js:231:21
          2  100.0%          LazyCompile: ~readPackageScope internal/modules/cjs/loader.js:262:26
          1   50.0%            LazyCompile: ~trySelf internal/modules/cjs/loader.js:383:17
          1   50.0%            LazyCompile: ~Module._extensions..js internal/modules/cjs/loader.js:1008:37
          2   33.3%        LazyCompile: ~Module._findPath internal/modules/cjs/loader.js:436:28
          2  100.0%          LazyCompile: ~Module._resolveFilename internal/modules/cjs/loader.js:731:35
          2  100.0%            LazyCompile: ~Module._load internal/modules/cjs/loader.js:648:24
          1   16.7%        LazyCompile: ~stat internal/modules/cjs/loader.js:123:14
          1  100.0%          LazyCompile: ~tryFile internal/modules/cjs/loader.js:326:17
          1  100.0%            LazyCompile: ~tryExtensions internal/modules/cjs/loader.js:342:23
          1   16.7%        LazyCompile: ~realpathSync fs.js:1568:22
          1  100.0%          LazyCompile: ~toRealPath internal/modules/cjs/loader.js:335:20
          1  100.0%            LazyCompile: ~tryFile internal/modules/cjs/loader.js:326:17
          5    8.2%      LazyCompile: ~toRealPath internal/modules/cjs/loader.js:335:20
          4   80.0%        LazyCompile: ~tryFile internal/modules/cjs/loader.js:326:17
          4  100.0%          LazyCompile: ~tryExtensions internal/modules/cjs/loader.js:342:23
          3   75.0%            LazyCompile: ~Module._findPath internal/modules/cjs/loader.js:436:28
          1   25.0%            LazyCompile: ~tryPackage internal/modules/cjs/loader.js:279:20
          1   20.0%        LazyCompile: ~Module._findPath internal/modules/cjs/loader.js:436:28
          1  100.0%          LazyCompile: ~resolveMainPath internal/modules/run_main.js:8:25
          1  100.0%            LazyCompile: ~executeUserEntryPoint internal/modules/run_main.js:53:31
          5    8.2%      LazyCompile: *log /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/dist/perf/better-console-logger.service.js:47:8
          4   80.0%        LazyCompile: *log /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/dist/perf/better-logger.service.js:52:8
          4  100.0%          Eval: ~<anonymous> /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/dist/perf/perf-better-logger.js:1:1
          4  100.0%            LazyCompile: ~Module._compile internal/modules/cjs/loader.js:953:37
          1   20.0%        LazyCompile: *<anonymous> /home/h4ad/Projects/opensource/performance-test-nestjs/test-performance/dist/perf/perf-better-logger.js:1:1
          1  100.0%          LazyCompile: ~Module._compile internal/modules/cjs/loader.js:953:37
          1  100.0%            LazyCompile: ~Module._extensions..js internal/modules/cjs/loader.js:1008:37
    

    Source

    And the CPU profiling now looks like:

    image

    And the time to perform the log looks consistent between NodeJS environments.

    perf-better-nodejs12.cpuprofile.zip perf-better-nodejs16.cpuprofile.zip perf-better-nodejs19.cpuprofile.zip

    Finally, about the performance improvements, this is the result running on NodeJS 16:

    Logger x 7,127 ops/sec ยฑ1.55% (87 runs sampled)
    BetterLogger x 60,055 ops/sec ยฑ1.90% (65 runs sampled)
    Console x 133,689 ops/sec ยฑ1.14% (90 runs sampled)
    

    Console is just console.log.

    An improvement of 8x in the performance when logging.

    I didn't make any breaking changes in the logs, but if we change from Intl.DateTimeFormat API to just new Date().toISOString(), the benchmark will look like:

    Logger x 7,165 ops/sec ยฑ1.80% (80 runs sampled)
    BetterLogger x 79,513 ops/sec ยฑ2.74% (62 runs sampled)
    Console x 140,275 ops/sec ยฑ1.61% (88 runs sampled)
    

    So let me know if worth to introduce some breaking changes just to have better performance when logging.

    To reproduce all those tests, see this gist: https://gist.github.com/H4ad/da838dfc33b2060504ca980644d804b5

    Does this PR introduce a breaking change?

    • [ ] Yes
    • [x] No

    Other information

    opened by H4ad 2
Releases(v9.2.1)
Owner
nestjs
A progressive Node.js framework for building efficient and scalable server-side applications ๐Ÿš€
nestjs
Catberry is an isomorphic framework for building universal front-end apps using components, Flux architecture and progressive rendering.

Catberry What the cat is that? Catberry was developed to help create "isomorphic/Universal" Web applications. Long story short, isomorphic/universal a

Catberry.js 801 Dec 20, 2022
:rocket: Progressive microservices framework for Node.js

Moleculer Moleculer is a fast, modern and powerful microservices framework for Node.js. It helps you to build efficient, reliable & scalable services.

MoleculerJS 5.5k Jan 4, 2023
๐Ÿฅš Born to build better enterprise frameworks and apps with Node.js & Koa

Features Built-in Process Management Plugin System Framework Customization Lots of plugins Quickstart Follow the commands listed below. $ mkdir showca

egg 18.3k Dec 29, 2022
A well documented set of tools for building node web applications.

Perk Framework Perk is a well documented set of tools for building node web applications. The goal of Perk is first and foremost to provide a well doc

Aaron Larner 179 Oct 26, 2022
A framework for real-time applications and REST APIs with JavaScript and TypeScript

A framework for real-time applications and REST APIs with JavaScript and TypeScript Feathers is a lightweight web-framework for creating real-time app

Feathers 14.3k Jan 1, 2023
MVC framework making it easy to write realtime, collaborative applications that run in both Node.js and browsers

Derby The Derby MVC framework makes it easy to write realtime, collaborative applications that run in both Node.js and browsers. Derby includes a powe

DerbyJS 4.7k Dec 23, 2022
Use full ES2015+ features to develop Node.js applications, Support TypeScript.

ThinkJS Use full ES2015+ features to develop Node.js applications, Support TypeScript. ็ฎ€ไฝ“ไธญๆ–‡ๆ–‡ๆกฃ Installation npm install -g think-cli Create Application

ThinkJS 5.3k Dec 30, 2022
๐Ÿ” A Node.js Serverless Framework for front-end/full-stack developers. Build the application for next decade. Works on AWS, Alibaba Cloud, Tencent Cloud and traditional VM/Container. Super easy integrate with React and Vue. ๐ŸŒˆ

Midway - ไธ€ไธช้ขๅ‘ๆœชๆฅ็š„ไบ‘็ซฏไธ€ไฝ“ Node.js ๆก†ๆžถ English | ็ฎ€ไฝ“ไธญๆ–‡ ?? ๆฌข่ฟŽ่ง‚็œ‹ Midway Serverless 2.0 ๅ‘ๅธƒไผšๅ›žๆ”พ๏ผš https://www.bilibili.com/video/BV17A411T7Md ใ€ŠMidway Serverless ๅ‘ๅธƒ

Midway.js 6.3k Jan 8, 2023
Fast and low overhead web framework, for Node.js

An efficient server implies a lower cost of the infrastructure, a better responsiveness under load and happy users. How can you efficiently handle the

Fastify 26k Jan 2, 2023
๐Ÿš€ The Node.js Framework highly focused on developer ergonomics, stability and confidence

Sponsored by FOSS United is a non-profit foundation that aims at promoting and strengthening the Free and Open Source Software (FOSS) ecosystem in Ind

AdonisJS Framework 13.4k Dec 31, 2022
A template project for building high-performance, portable, and safe serverless functions in Vercel.

Tutorial | Demo for image processing | Demo for tensorflow This is a Next.js project bootstrapped with create-next-app. This project is aimed to demon

Second State 63 Dec 8, 2022
Fast, unopinionated, minimalist web framework for node.

Fast, unopinionated, minimalist web framework for node. const express = require('express') const app = express() app.get('/', function (req, res) {

null 59.5k Jan 5, 2023
Realtime MVC Framework for Node.js

Website Get Started Docs News Submit Issue Sails.js is a web framework that makes it easy to build custom, enterprise-grade Node.js apps. It is design

Balderdash 22.4k Dec 31, 2022
Node.js framework

Node.js framework Total.js framework is a framework for Node.js platfrom written in pure JavaScript similar to PHP's Laravel or Python's Django or ASP

Total.js 4.2k Jan 2, 2023
:evergreen_tree: Modern Web Application Framework for Node.js.

Trails is a modern, community-driven web application framework for Node.js. It builds on the pedigree of Rails and Grails to accelerate development by

Trails 1.7k Dec 19, 2022
A serverless web framework for Node.js on AWS (CloudFormation, CloudFront, API Gateway, Lambda)

---- Sorry, this project is not maintained anymore. ---- dawson is a serverless web framework for Node.js on AWS (CloudFormation, CloudFront, API Gate

dawson 717 Dec 30, 2022
Zeronode - minimal building block for NodeJS microservices

Zeronode - minimal building block for NodeJS microservices Why Zeronode? Installation Basics Benchmark API Examples Basic Examples Basic Examples [Adv

Steadfast 120 Oct 21, 2022
LoopBack makes it easy to build modern API applications that require complex integrations.

LoopBack makes it easy to build modern applications that require complex integrations. Fast, small, powerful, extensible core Generate real APIs with

StrongLoop and IBM API Connect 4.4k Jan 4, 2023
Build Amazon Simple Queue Service (SQS) based applications without the boilerplate

sqs-consumer Build SQS-based applications without the boilerplate. Just define an async function that handles the SQS message processing. Installation

BBC 1.4k Dec 26, 2022