First, Nestjs pipeline

1. About pipes in Nestjs

Pipes in Nestjs convert input data into desired output. In addition, it can handle tokens that may throw exceptions when the data is incorrect.

Create and use pipes in Nestjs

1. Create a pipe

nest g pipe user
Copy the code

After the pipeline is created, the following code is generated:

import { ArgumentMetadata, Injectable, PipeTransform} from '@nestjs/common';
@Injectable()
export class UserPipe implements PipeTransform {
    transform(value: any, metadata: ArgumentMetadata) {
        // This allows you to modify the incoming value and verify the validity of the incoming value
        returnvalue; }}Copy the code

2. Use pipes

import { Controller,Get,UsePipes,Query} from '@nestjs/common';
import { UserPipe } from '.. /.. /user.pipe';
@Controller('user')
export class UserController {
    @Get()
    index(){
        return 'User page';
    }
    @Get('pipe')
    @UsePipes(new UserPipe())
    pipe(@Query() info){
        console.log(info);
        return `this is Pipe`; }}Copy the code

Second, Nestjs guard

1. Guards in Nestjs

The guard is a class that uses the @Injectable() decorator. Guards should implement the CanActivate interface.

The guard has a separate responsibility. They determine whether a request should be handled by a routing handler. So far, the access restriction logic has been mostly in middleware. This is good because things like token validation or attaching attributes to the Request object are not strongly associated with a particular route. But middleware is pretty dumb. It does not know which handler will be executed after calling the next() function. On the other hand, the guard has access to the ExecutionContext object, so we know exactly what will be executed.

To be clear: in Nextjs if we want to do permissions we can do it in the guard, or we can do it in the middleware.

2. Create guards in Nestjs and configure guards separately in controller

1. Create guards

nest g guard auth

After the guard is created, the following code is generated:

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
    canActivate(
        context: ExecutionContext,
        ): boolean | Promise<boolean> | Observable<boolean> {
        return true; }}Copy the code

2. Use guards

@Get('guard')
@UseGuards(AuthGuard)
guard(@Query() info){
    console.log(info);
    return`thisis guard`;
}
Copy the code

You can also add it directly to the controller

@Controller('cats')
@UseGuards(RolesGuard)
export class CatsController {}
Copy the code

3. Use guards in Nestjs, and global configuration guards

1. Create guards

nest g guard auth
Copy the code

After the guard is created, the following code is generated:

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
    canActivate(
        context: ExecutionContext,
        ): boolean | Promise<boolean> | Observable<boolean> {
        return true; }}Copy the code

2. Use guards globally

// Global guard
app.useGlobalGuards(new AuthGuard());
Copy the code

Get cookies and Session in Nestj’s guard

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
    canActivate(
        context: ExecutionContext,
        ): boolean | Promise<boolean> | Observable<boolean> {
        console.log(context.switchToHttp().getRequest().cookies);
        console.log(context.switchToHttp().getRequest().session);
        return true; }}Copy the code