Search code examples
node.jshapi

How do I fix the error when using Validation?


I am trying to add a validation for my API. I get the following error when compiling the project.

(node:13800) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Invalid schema content:

Here is the code:

    const Joi = require('joi');

    async function response(request) 
    {
        let email = request.payload.email;
        let userRecord = await User.find();
        userRecord = userRecord.find(x => x.email == email);

        if (!userRecord)
        {
            throw Boom.unauthorized();
        }

        if (!userRecord.checkPassword(request.payload.password))
        {
           throw Boom.unauthorized();
        }
    
        let token = await CreateUpdateToken(userRecord);

        return {
         bearerToken: [token.access_token]
        };
    }
   
    module.exports = {
        method: 'POST',
        path: '/api/v1/auth',
        handler: response,
        options: {
            validate: {
                payload: {
                    password: Joi.string()
                }
            }
        }
    }

Note: If I delete "password: Joi.string()" the error disappears


Solution

  • You need an object schema to validate your payload in hapi:

    validate: {
      payload: Joi.object({
        password: Joi.string().trim().required()
      })
    }