0

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
);
2
  • Define it doesn't work Commented May 22, 2020 at 14:00
  • @AyushGupta, but is it something I'm doing wrong? Commented May 22, 2020 at 14:00

2 Answers 2

2

the problem is that the celebrate function creates and returns a middleware, so the middleware returned by the celebrate function must be passed as second parameter to the post but you're passing a function that execute the celebrate method instead, so validateCreate should be:

module.exports = {
    validateCreate: celebrate({...})
}
Sign up to request clarification or add additional context in comments.

Comments

1

I think you did something wrong with module exports

try something like this:

module.exports = {
    validateCreate: function() {},
    otherMethod: function() {},
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.