function zodErrorMap(error) {
  const errors = {};

  if (error.issues) {
      error.issues.forEach((issue) => {
          const propName = issue.path[0];
          const message = issue.message;

          if (!errors[propName]) {
              errors[propName] = [message];
          } else {
              errors[propName].push(message);
          }
      });
  } else {
      errors['unknown'] = ['Unknown error occurred'];
  }

  return errors;
}


export { zodErrorMap };



/* function zodErrorMap (zodIssues) {

  const errors = {}; 

  zodIssues.forEach(issue => {
    const propName = issue.path[0];
    const message = issue.message;

    // Si no existe un error en ese campo lo añadimos en una nueva propiedad del objeto 
    //y poniendo el mensaje de error en un array
    if (!errors[propName]) {
      errors[propName] =  [message];   
      return   
    }
    // En cambio, si ya existe un error en ese elemento lo añadimos al final del array de mensajes 
    errors[propName] = [...errors[propName], message];
    
  });

  return errors;
}

export { zodErrorMap }; */


function zodErrorMap(zodIssues) {
    console.log('zodIssues: ', zodIssues);
    const errors = {};

    zodIssues.forEach((issue) => {
        const propName = issue.path[0];
        const message = issue.message;

        // Si no existe un error en ese campo lo añadimos en una nueva propiedad del objeto 
        //y poniendo el mensaje de error en un array
        if (!errors[propName]) {
            errors[propName] = [message];
            return;
        }
        // En cambio, si ya existe un error en ese elemento 
        //lo añadimos al final del array de mensajes 
        errors[propName] = [...errors[propName], message];
    });

    return errors;
}

export { zodErrorMap };



//import { zodErrorMap } from "../../helpers/zodError.js";
import { zodErrorMap } from "../../helpers/zodErrorMap.js";
import { questionSchema } from "../../schemas/questionShema.js";
import insertQuestionModel from "../../models/entries/insertQuestionModel.js";

const newQuestionController = async (req, res, next) => {
    console.log('req.insertId2: ', req.userId);

    try {
        //const {question_title, question_description}=req.body;
        
        // validation fields
        /* if(!question_title||!question_description){
            console.error('faltan campos');
        } */
        // validation length
        /* if (question_description > 280) {
            throw  generateError('Debes enviar un texto menor de 280 caracteres', 400);
        } */

        // validation schema
        const { sucess, data: questionDataBody, error } = questionSchema.safeParse(req.body);
        console.log('questionDataBody:', questionDataBody); // Add this line
        console.log('error:', error); // Add this line

        if (!sucess) {
            const errors = zodErrorMap(error?.issues);
            console.log('errors:', errors);
            return res.status(400).send({ error: errors });
        }
        const { question_title, question_description } = questionDataBody;


        // insert question
        const id = await insertQuestionModel(question_title, question_description,req.userId);

        // send response
        res.status(201).send({
            status:'ok',
            message:'insert question in db',
            data:{
                question:{
                    questionId: id,
                    question_title,
                    question_description,
                    userId: req.userId,
                    createdAt: new Date(),
                },
            },
        });
    
    } catch (err) {
        next(err);
    }
};
export default newQuestionController;

get this error:
error: undefined
TypeError: Cannot read properties of undefined (reading 'issues')
    at zodErrorMap (file:///Users/XShhh/BoHB/FranK-org/new-2024_04_24_3/frankenstein/back/src/helpers/zodErrorMap.js:4:13)
    at newQuestionController (file:///Users/XShhh/BoHB/FranK-org/new-2024_04_24_3/frankenstein/back/src/controllers/questions/newQuestionController.js:27:28)
    at Layer.handle [as handle_request] (/Users/XShhh/BoHB/FranK-org/new-2024_04_24_3/frankenstein/back/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/XShhh/BoHB/FranK-org/new-2024_04_24_3/frankenstein/back/node_modules/express/lib/router/route.js:149:13)
    at authUser (file:///Users/XShhh/BoHB/FranK-org/new-2024_04_24_3/frankenstein/back/src/middlewares/auth.js:27:9)
    at Layer.handle [as handle_request] (/Users/XShhh/BoHB/FranK-org/new-2024_04_24_3/frankenstein/back/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/XShhh/BoHB/FranK-org/new-2024_04_24_3/frankenstein/back/node_modules/express/lib/router/route.js:149:13)
    at Route.dispatch (/Users/XShhh/BoHB/FranK-org/new-2024_04_24_3/frankenstein/back/node_modules/express/lib/router/route.js:119:3)
    at Layer.handle [as handle_request] (/Users/XShhh/BoHB/FranK-org/new-2024_04_24_3/frankenstein/back/node_modules/express/lib/router/layer.js:95:5)
    at /Users/XShhh/BoHB/FranK-org/new-2024_04_24_3/frankenstein/back/node_modules/express/lib/router/index.js:284:15
POST /newquestion 500 28.213 ms - 85