I'm new in NodeJS, and I'm struggling a little bit on this. I'm using Express and to validate the data, I'm using Celebrate.
I've got a route.js file, where I make a POST request, using a function from another file to do so (it's the create function, from MyController. It works fine! But when I try to do the same thing to my validator, it doesn't work.
So let's take a look at the code.
The route.js file:
const express = require("express");
const MyController = require("./controllers/MyController");
const MyValidator= require("./validators/MyValidator");
const routes = express.Router();
routes.post("/path", MuValidator.validateCreate, MyController.create);
The MyValidator file:
module.exports = {
validateCreate() {
celebrate({
[Segments.HEADERS]: Joi.object({
authorization: Joi.string().required(),
}).unknown(),
[Segments.BODY]: Joi.object().keys({
userId: Joi.string().required(),
title: Joi.string().required(),
description: Joi.string().required(),
value: Joi.number().required(),
dueDate: Joi.string().required(),
}),
});
},
}
IMPORTANT: I only get this working, if I write the validation code directly on my route, like this:
routes.post(
"/path",
celebrate({
[Segments.HEADERS]: Joi.object({
authorization: Joi.string().required(),
}).unknown(),
[Segments.BODY]: Joi.object().keys({
userId: Joi.string().required(),
title: Joi.string().required(),
description: Joi.string().required(),
value: Joi.number().required(),
dueDate: Joi.string().required(),
}),
}),
MyController.create
);