Search code examples
node.jsjoi

What am I doing wrong here with the nodejs and joi


I am new to nodejs, so pardon my syntax and code flow. I am trying to understand how to use Joi (using the standar joi and not the @hapi/joi)

middleware validateRequest.js

const Joi = require('joi');

module.exports.validateRequest = (schema) => {
    return (req, res, next) => {
        const options = {
            abortEarly: false, // include all errors
            allowUnknown: true, // ignore unknown props
            stripUnknown: true // remove unknown props
        };

        const { err, value } = schema.validate(req.body, options);

        if (err) {
            next(`Validation error: ${err.details.map(x => x.message).join(', ')}`);
        } else {
            req.body = value;
            next();
        }
    };
};

My schema is defined as dataRepo.js

const Joi = require('joi');    
module.exports.validateDataRepo =  Joi.object().keys({
                ownerId: Joi.string()
                .min(5)
                .max(30)
                .required(),
                email: Joi.string()
                .email()
                .min(5)
                .max(50)
                .optional(),
                uri: Joi.string().uri().required()
                });

My route is defined as follows:

const express = require('express');
const routes = express.Router();
const {validateDataRepo} = require('../schemas/datarepo');
const {validateRequest} = require('../middleware/validateRequest');



const genericHandler = (req, res, next ) => {
    //const data = req.body;
    res.status(200).json({
        status: 'success',
        time: new Date().toISOString(),
        data: req.body
    })
}
console.log(validateDataRepo['$_root'])
routes.route('/')
    .get(genericHandler)

routes.post('/', validateRequest(validateDataRepo), genericHandler);

module.exports = routes;

When I call POST and pass in { "ownerId": "t"}

I expect it to throw an error, on the min size, but I am not getting any errors from Joi.

Would really appreciate if someone could point me in the right directions.

Thanx Sam


Solution

  • schema.validate() returns an object containing a property called error, not err:

    const { error, value } = schema.validate(req.body, options);
    
    if (error) { … }