Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

TypeError: Cannot read property 'length' of undefined

Boa tarde,

Ao refatorar meu model Atendimento estou recebendo resposta "TypeError: Cannot read property 'length' of undefined". Baixei do github o projeto final e resulta no mesmo erro.

const axios  = require('axios');
const moment = require('moment');

const repositories = require ('../repositories/customerService');

class CustomerService {

    constructor() { 
        this.validDate = ({scheduledDate, createdAt}) => moment(scheduledDate).isSameOrAfter(createdAt);
        this.validCustomer = ({ clientLength }) => clientLength >= 11;

        this.validate = params => {
            this.validations.filter(field => {
                const { name } = field;
                const parameter = params[name];

                return !field.valid(parameter);
            });
        };   

        this.validations = [
            {
                name: 'date',
                valid: this.validDate,
                message: 'The date must be greater than or equal to the current date'
            },{
                name: 'client',
                valid: this.validCustomer,
                message: 'Customer name must contain more than five characters'
            }
        ];
    }

    add(customerService, res){
        const createdAt = new Date();
        const { client, scheduledDate } = customerService;


        const params = {
            date: {scheduledDate, createdAt},
            client: {clientLength: client.length}
        }

        const errors = this.validate(params);
        const checkErrors = errors.length;

        if (checkErrors){
            return new Promise((resolve, reject) => reject(errors));
        } else {
            customerService = {
                createdAt,
                ... customerService
            };

            return repositories.add(customerService)
                .then((result) => {
                    const id = result.insertId;
                    return {
                        id, 
                        ...customerService 
                    };
                });
        };
    }

    list(){
        return repositories.list();
    }

    listById(id, res){
        const sql = `SELECT * FROM CustomerService WHERE id = ?`;

        connection.query(sql, id, async (error, result) => {
            const customerService = result[0];
            const cpf = customerService.client; 

            if(error){
                res.status(400).json(error);
            } else {
                const { data } = await axios.get(`http://127.0.0.1:8082/${cpf}`);
                customerService.client = data;

                res.status(200).json(customerService);
            };
        });
    }

    update(id, data, res) {
        const sql = `UPDATE CustomerService SET ? WHERE id = ?`;

        connection.query(sql,[data,id], (error, result) => {
            if(error){
                res.status(400).json(error);
            } else {
                res.status(200).json({id});
            };
        });
    }

    delete(id, res) {
        const sql = `DELETE FROM CustomerService WHERE id = ?`

        connection.query(sql, id, (error, result) => {
            if(error){
                res.status(400).json(error);
            } else {
                res.status(200).json({id});
            };
        })
    }
}

module.exports = new CustomerService;
2 respostas
solução!

Depois que retornamos um objeto booleano nessa linha: const errors = this.validate(params); Não precisamos mais fazer a checagem dos erros em: const checkErrors = errors.length; Pois já teremos uma validação para passar pelo "if", sendo assim, basta retirar a constante checkErrors e substituir no "if" por errors. Espero ter ajudado :D

Obrigado pela ajuda

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software