# All files / nodejs-homework-API/routes/api/validation validationContact.js

100% Statements 13/13
100% Branches 2/2
100% Functions 3/3
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    501x

    1x

    1x

    1x
    6x
    6x
    3x
    3x

    3x

    1x
    3x

    1x
    3x

     const Joi = require("joi");

    const schemaCreateContact = Joi.object({
      name: Joi.string().alphanum().min(3).max(30).required().trim(),
      email: Joi.string().email().min(3).max(30).required(),
      phone: Joi.string()
        .regex(/^[0-9]{10}$/)
        .messages({
          "string.pattern.base": `Phone number must have 10 digits and only numbers characters.`,
        })
        .required(),
      password: Joi.string().required(),
      subscription: Joi.string().optional(),
      token: Joi.string().optional(),
    }).min(4);

    const schemaUpdateContact = Joi.object({
      name: Joi.string().alphanum().min(3).max(30).optional().trim().optional(),
      email: Joi.string().email().min(3).max(30).optional(),
      phone: Joi.string()
        .regex(/^[0-9]{10}$/)
        .messages({
          "string.pattern.base": `Phone number must have 10 digits and only numbers characters.`,
        })
        .optional(),
      password: Joi.string().optional(),
      subscription: Joi.string().optional(),
      token: Joi.string().optional(),
    }).min(1);

    const validate = (schema, obj, next) => {
      const { error } = schema.validate(obj);
      if (error) {
        const [{ message }] = error.details;
        return next({
          status: 400,
          message: `Filed: ${message.replace(/"/g, "")}`,
        });
      }
      next();
    };

    module.exports.createContact = (req, _res, next) => {
      return validate(schemaCreateContact, req.body, next);
    };

    module.exports.update = (req, _res, next) => {
      return validate(schemaUpdateContact, req.body, next);
    };