Book Image

Nest.js: A Progressive Node.js Framework

By : Greg Magolan, Patrick Housley, Adrien de Peretti, Jay Bell, David Guijarro
Book Image

Nest.js: A Progressive Node.js Framework

By: Greg Magolan, Patrick Housley, Adrien de Peretti, Jay Bell, David Guijarro

Overview of this book

Nest.js is a modern web framework built on a Node.js Express server. With the knowledge of how to use this framework, you can give your applications an organized codebase and a well-defined structure. The book begins by showing how to use Nest.js controllers, providers, modules, bootstrapping, and middleware in your applications. You’ll learn to use the authentication feature of Node.js to manage the restriction access in your application, and how to leverage the Dependency Injection pattern to speed up your application development. As you advance through the book, you'll also see how Nest.js uses TypeORM—an Object Relational Mapping (ORM) that works with several relational databases. You’ll use Nest.js microservices to extract part of your application’s business logic and execute it within a separate Nest.js context. Toward the end of the book, you’ll learn to write tests (both unit tests as well as end-to-end ones) and how to check the percentage of the code your tests cover. By the end of this book, you’ll have all the knowledge you need to build your own Nest.js applications.
Table of Contents (16 chapters)

Sending data

The previous microservice handler was very contrived. It is more likely that microservice handlers will be implemented to perform some processing on data and return some value. In a normal HTTP handler, we would use @Req or @Body to extract the data from the HTTP request’s body. Since microservice handlers have no HTTP context, they take input data as a method parameter.

@Controller()
export class UserController {
    @Client({transport: Transport.TCP, options: { port: 5667 }})
    client: ClientProxy

    @Post('users')
    public async create(@Req() req, @Res() res) {
        this.client.send({cmd: 'users.index'}, {}).subscribe({
            next: users => {
                res.status(HttpStatus.OK).json(users);
            },
            error: error => {
                res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(error);
            }
        });
    }

    @MessagePattern({cmd: 'users.create'})
    public async rpcCreate...