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