با یه تیر دو نشان بزن🎯، هدیه 6 میلیونی(متخصص لینوکس) به همراه ۲0٪ تخفیف روی همه دوره‌های متخصص😍
۰ ثانیه
۰ دقیقه
۰ ساعت
۱ هادی جیبر
بررسی error در cli
جامعه نود جی اس ایجاد شده در ۰۸ مهر ۱۴۰۳

با سلام

با نوشتن این کد در فایل cli.js هنگام اجرای new contact با error مواجه می‌شوم :

import readline from 'readline/promises';

import {stdin as input , stdout as output} from 'process';

import {contact , sequelize} from './models/index.js'

 

const rl = readline.createInterface({input,output});

async function help() {

 

 console.log('n:NewContact\nd:DeleteContact\nL:ShowContact\nq:quit\n');

 console.log('-----');

const answer = await rl.question('Enter your input:');

 

  if( answer === 'n'){

      console.log('nnnnn');

      await createNewContactCli();

       help();

  }

  else if(answer === 'd'){

    console.log('ddddd');

    help();

  }

  else if(answer === 'l'){

    console.log('List is:');

     await showContactsListCli();

    help();

  }

  else if(answer == 'q'){

    quit();

    return;

  };

};

help();

 

function quit(){

  rl.close();

}

 

async function showContactsListCli()

{

  // const contacts = await contact.findAll({

   const contacts =  contact.findAll({

    attributes : [

      'id',

     'firstName',

  'lastName' ,

  'mobilePhone',

  'isFavorite',

  ]

   });

 

console.log(contacts);

};

async function createNewContactCli() {

 

 var firstName = rl.question('Please enter your firstName:');

  var lastName = rl.question('Please enter your LastName:' );

  var mobilePhone = rl.question('your mobilePhone:');

  var isFavorite = rl.question('your Favorite:');

 

  const id = await contact.create({

    firstName,

    lastName,

    mobilePhone,

    isFavorite: ['yes', 'Yes', 'YES'].includes(isFavorite),

 });

 console.log(`The Contact # ${id} ${firstName} ${lastName} is created`);

 

};

متن Error به این صورت است که :

Connection has been established successfully.
true
true
n:NewContact
d:DeleteContact
L:ShowContact
q:quit

-----
Enter your input:n
nnnnn
Please enter your firstName:D:\7Learn NodeJS Backend Expert\NodejsApp\ContactListSequelize\node_modules\sequelize\lib\instance-validator.js:50
     throw new sequelizeError.ValidationError(null, this.errors);
           ^

ValidationError [SequelizeValidationError]: string violation: firstName cannot be an array or an object,
string violation: lastName cannot be an array or an object,
string violation: mobilePhone cannot be an array or an object
   at InstanceValidator._validate (D:\7Learn NodeJS Backend Expert\NodejsApp\ContactListSequelize\node_modules\sequelize\lib\instance-validator.js:50:13)
   at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
   at async InstanceValidator._validateAndRunHooks (D:\7Learn NodeJS Backend Expert\NodejsApp\ContactListSequelize\node_modules\sequelize\lib\instance-validator.js:60:7)
   at async InstanceValidator.validate (D:\7Learn NodeJS Backend Expert\NodejsApp\ContactListSequelize\node_modules\sequelize\lib\instance-validator.js:54:12)
   at async model.save (D:\7Learn NodeJS Backend Expert\NodejsApp\ContactListSequelize\node_modules\sequelize\lib\model.js:2426:7)
   at async contact.create (D:\7Learn NodeJS Backend Expert\NodejsApp\ContactListSequelize\node_modules\sequelize\lib\model.js:1362:12)
   at async createNewContactCli (file:///D:/7Learn%20NodeJS%20Backend%20Expert/NodejsApp/ContactListSequelize/cli.js:68:14)
   at async help (file:///D:/7Learn%20NodeJS%20Backend%20Expert/NodejsApp/ContactListSequelize/cli.js:21:7) {
 errors: [
   ValidationErrorItem {
     message: 'firstName cannot be an array or an object',
     type: 'string violation',
     path: 'firstName',
     value: Promise { <pending> },
     origin: 'CORE',
     instance: contact {
       dataValues: {
         id: null,
         firstName: Promise { <pending> },
         lastName: Promise { <pending> },
         mobilePhone: Promise { <pending> },
         isFavorite: false,
         updatedAt: 2024-09-29T05:56:18.394Z,
         createdAt: 2024-09-29T05:56:18.394Z
       },
       _previousDataValues: {
         firstName: undefined,
         lastName: undefined,
         mobilePhone: undefined,
         isFavorite: undefined
       },
       uniqno: 1,
       _changed: Set(4) { 'firstName', 'lastName', 'mobilePhone', 'isFavorite' },
       _options: {
         isNewRecord: true,
         _schema: null,
         _schemaDelimiter: '',
         attributes: undefined,
         include: undefined,
         raw: undefined,
         silent: undefined
       },
       isNewRecord: true
     },
     validatorKey: 'not_a_string',
     validatorName: null,
     validatorArgs: []
   },
   ValidationErrorItem {
     message: 'lastName cannot be an array or an object',
     type: 'string violation',
     path: 'lastName',
     value: Promise { <pending> },
     origin: 'CORE',
     instance: contact {
       dataValues: {
         id: null,
         firstName: Promise { <pending> },
         lastName: Promise { <pending> },
         mobilePhone: Promise { <pending> },
         isFavorite: false,
         updatedAt: 2024-09-29T05:56:18.394Z,
         createdAt: 2024-09-29T05:56:18.394Z
       },
       _previousDataValues: {
         firstName: undefined,
         lastName: undefined,
         mobilePhone: undefined,
         isFavorite: undefined
       },
       uniqno: 1,
       _changed: Set(4) { 'firstName', 'lastName', 'mobilePhone', 'isFavorite' },
       _options: {
         isNewRecord: true,
         _schema: null,
         _schemaDelimiter: '',
         attributes: undefined,
         include: undefined,
         raw: undefined,
         silent: undefined
       },
       isNewRecord: true
     },
     validatorKey: 'not_a_string',
     validatorName: null,
     validatorArgs: []
   },
   ValidationErrorItem {
     message: 'mobilePhone cannot be an array or an object',
     type: 'string violation',
     path: 'mobilePhone',
     value: Promise { <pending> },
     origin: 'CORE',
     instance: contact {
       dataValues: {
         id: null,
         firstName: Promise { <pending> },
         lastName: Promise { <pending> },
         mobilePhone: Promise { <pending> },
         isFavorite: false,
         updatedAt: 2024-09-29T05:56:18.394Z,
         createdAt: 2024-09-29T05:56:18.394Z
       },
       _previousDataValues: {
         firstName: undefined,
         lastName: undefined,
         mobilePhone: undefined,
         isFavorite: undefined
       },
       uniqno: 1,
       _changed: Set(4) { 'firstName', 'lastName', 'mobilePhone', 'isFavorite' },
       _options: {
         isNewRecord: true,
         _schema: null,
         _schemaDelimiter: '',
         attributes: undefined,
         include: undefined,
         raw: undefined,
         silent: undefined
       },
       isNewRecord: true
     },
     validatorKey: 'not_a_string',
     validatorName: null,
     validatorArgs: []
   }
 ]
}

Node.js v18.15.0
 

 

و هنگام اجرای List Contact نیز در هنگام نمایش لیست در حالت Pending  میماندو لیست را نمایش نمی‌دهد در صورتی که کد مشابه را از طریق route اجرا می‌کنم مشکلی ندارد و لیست دیتابیس را نمایش می‌دهد

لطفا بررسی بفرمایید

سلام،

مشکلی که در کد شما هست به نحوه استفاده از متد question در readline برمی‌گرده. این متد به صورت غیرفعال (async) عمل نمی‌کنه و در واقع یه Promise برمی‌گردونه. برای اینکه این مسئله رو حل کنیم، باید از await استفاده کنیم.

یه مشکل دیگه هم مربوط به findAll در متد showContactsListCli هست. چون از await استفاده نکردین، این متد همچنان یه Promise برمی‌گردونه که در حالت Pending می‌مونه. برای اینکه این مشکل هم حل بشه، باید await رو به findAll اضافه کنیم.

برای رفع این مشکلات، می‌تونید به شکل زیر کدتون رو تغییر بدین:

  1. توی متد rl.question از await استفاده کنید تا ورودی کاربر به درستی گرفته بشه.
  2. توی findAll هم await رو اضافه کنید تا لیست مخاطبین به درستی از دیتابیس خونده بشه.

کد اصلاح شده به شکل زیر درمیاد:

import readline from 'readline/promises';
import { stdin as input, stdout as output } from 'process';
import { contact, sequelize } from './models/index.js';
const rl = readline.createInterface({ input, output });
async function help() {
  console.log('n:NewContact\nd:DeleteContact\nL:ShowContact\nq:quit\n');
  console.log('-----');
  const answer = await rl.question('Enter your input: ');
  if (answer === 'n') {
    console.log('nnnnn');
    await createNewContactCli();
    help();
  } else if (answer === 'd') {
    console.log('ddddd');
    help();
  } else if (answer === 'l') {
    console.log('List is:');
    await showContactsListCli();
    help();
  } else if (answer == 'q') {
    quit();
    return;
  }
}
help();
function quit() {
  rl.close();
}
async function showContactsListCli() {
  const contacts = await contact.findAll({
    attributes: ['id', 'firstName', 'lastName', 'mobilePhone', 'isFavorite'],
  });
  console.log(contacts);
}
async function createNewContactCli() {
  const firstName = await rl.question('Please enter your firstName: ');
  const lastName = await rl.question('Please enter your LastName: ');
  const mobilePhone = await rl.question('your mobilePhone: ');
  const isFavorite = await rl.question('your Favorite: ');
  const newContact = await contact.create({
    firstName,
    lastName,
    mobilePhone,
    isFavorite: ['yes', 'Yes', 'YES'].includes(isFavorite),
  });
  console.log(`The Contact # ${newContact.id} ${firstName} ${lastName} is created`);
}
محسن موحد ۰۹ مهر ۱۴۰۳، ۱۳:۲۷