celebrate npm package with Nest Framework

-1

There is some way to use the NPM celebrate package with Nest Framework ? In the documentation only refer to class-validator , but although this has many advantages I used with Express and other frameworks the middleware celebrate to validate the request. In the case of Nest the configuration of middleware becomes the app.module.ts , but in others as routing-controllers the decorator @UseBefore is used for the middlewares in the controllers, that is why I would appreciate any explanation, example or documentation of how to use this middleware with Nest. Thanks !!

    
asked by Yariel Rojas Gonzalez 12.12.2018 в 19:35
source

1 answer

1

Here is the solution:

In a file dedicated to validations, create the middlware with the scheme to be used by celebrate (this would be a simple example for an authentication):

import { celebrate, Joi } from 'celebrate';

export const authenticate = celebrate({
    headers: Joi.object().keys({
        client: Joi.string().required(),
        application: Joi.string().required(),
    }).unknown(),
    body: Joi.object().keys({
        email: Joi.string().email().required(),
        password: Joi.string().required(),
    }),
});

How to use it later? You import it into the module and apply it as middleware , since celebrate returns a function of the form function(req, res, next) :

import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
// Otros imports ...
import { authenticate } from './validations/authenticate.validation';


@Module({
    imports: [ // Tus imports... ],
    controllers: [ // Tus controladoras... ],
    providers: [ // Tus providers... ],
})
export class AuthenticationModule implements NestModule {
    configure(consumer: MiddlewareConsumer) {
        // Validate Login.
        consumer.apply(authenticate).forRoutes({ path: 'security/login', method: RequestMethod.POST });
    }
}

The path defined in the configuration must obviously coincide with the endpoint of the controller:

import {
    Body,
    Post,
    Headers,
    Controller,
} from '@nestjs/common';

@Controller('security')
export class AuthenticationController {

    @Post('login')
    async authenticate(
        @Body('email') email: string,
        @Body('password') password: string,
        @Headers('application') application: string): Promise<any> {

        // Autenticar usuario
    }
}

You can also see:

link

link

    
answered by 20.12.2018 / 21:12
source