Как реорганизовать этот код node.js, чтобы избежать дублирования - PullRequest
0 голосов
/ 27 января 2019

Я пытаюсь настроить базовый скелет для моего демонстрационного проекта и пишу свою первую программу node.js.Приведенный ниже код работает для моего первого теста, но в нем есть дубликат - Получение соединения, Выполнение запроса (но другого), анализ выходных данных sql.Я хочу минимизировать это, потому что мне нужно написать больше блоков if-else, и это станет огромным и грязным кодом.

Детали подключения к базе данных обрабатываются в DatabaseManager.js

app.js

Строка № 8 и № 40:

var connect = require('./DatabaseManager');
bot.dialog('profileDialog', (session) => {
    session.send('You reached the profile intent. You said \'%s\'.', session.message.text);
    console.log('Creating a connection');

    var userMessage = session.message.text;

    // Here is the FIrst block
    if (userMessage.indexOf('Email') >= 0) {
      session.send('Your are looking for your email');

      connect(function(connection) {
        console.log('Reading rows from the Table...');

        request = new Request("select Email from StudentProfile where ID=1", function(err, rowCount) {

          if (err) {
            console.log('ERROR in QUERY');
          } else {
            console.log(rowCount + ' rows');
          }
          connection.close();
        });

        request.on('row', function(columns) { // Iterate through the rows using a callback
          columns.forEach(function(column) {
            if (column.value === null) {
              console.log('NULL');
            } else {
              session.send(column.value);
            }
          });
        });
        connection.execSql(request);
      });
      session.endDialog();
      return;
    } //end of email id if

    //Here is the second block with repeated functionality, but a different query.
    connect(function(connection) {
      console.log('Reading rows from the Table...');

      request = new Request("select FNAME from StudentProfile where ID=1", function(err, rowCount) {

        if (err) {
          console.log('ERROR in QUERY');
        } else {
          console.log(rowCount + ' rows');
        }
        connection.close();
      });

      request.on('row', function(columns) { // Iterate through the rows using a callback
        columns.forEach(function(column) {
          if (column.value === null) {
            console.log('NULL');
          } else {
            session.send(column.value);
          }
        });
      });
      connection.execSql(request);
    });


  } //end of dialog

).triggerAction({
  matches: 'profile'
}) //end of trigger

Я хочу реорганизовать этот код, чтобы сделать его простым и многократно используемым для других функций, передавая необходимые аргументы.

Я устал ниже, но return (column.value); оператор не работает:

function queryDatabase(colname) {
    connect(function (connection) {
        request = new Request('select Email from StudentProfile where SUID=1', function (err, rowCount) {

            if (err) {
                console.log('ERROR in QUERY');
                console.log(err);
            } else {
                console.log(rowCount + ' rows');
            }
            connection.close();
        });

        request.on('row', function (columns) {  // Iterate through the rows using a callback
            columns.forEach(function (column) {
                if (column.value === null) {
                    console.log('NULL');
                } else {
                    console.log(column.value);
                    return (column.value);
                }
            });
        });
        connection.execSql(request);
    });
}
bot.dialog('profileDialog',(session) => {
    session.send('You reached the profile intent. You said \'%s\'.', session.message.text);
    console.log('Creating a connection');

    var userMessage = session.message.text;

    if( userMessage.indexOf('Email') >= 0){
        session.send('Your are looking for your email');
        var messg = queryDatabase('Email');
        console.log(messg);
       session.endDialog();
       return;
     } //end of email id if

     else {
       session.send('Looking for something else');
       session.endDialog();
       return;
     }


} //end of dialog

).triggerAction({
matches: 'profile'
}) //end of trigger

Ответы [ 2 ]

0 голосов
/ 27 января 2019

Мне надоел следующий способ, но оператор return (column.value); не работает

Да, здесь нельзя использовать return.И потому, что он асинхронный, и потому, что он может выполняться несколько раз в цикле forEach.

Вместо этого используйте обратный вызов:

var connect = require('./DatabaseManager');

function queryDatabase(query, callback) {
//                            ^^^^^^^^
  connect(function(connection) {
    console.log('Reading rows from the Table...');

    const request = new Request(query, function(err, rowCount) {
//  ^^^^^ use local variable
      if (err) {
        console.log('ERROR in QUERY');
      } else {
        console.log(rowCount + ' rows');
      }
      connection.close();
    });

    request.on('row', function(columns) {
      columns.forEach(function(column) {
        if (column.value === null) {
          console.log('NULL');
        } else {
          callback(column.value);
//        ^^^^^^^^
        }
      });
    });
    connection.execSql(request);
  });
}

bot.dialog('profileDialog', (session) => {
  session.send('You reached the profile intent. You said \'%s\'.', session.message.text);
  console.log('Creating a connection');

  var userMessage = session.message.text;
  if (userMessage.indexOf('Email') >= 0) {
    session.send('Your are looking for your email');
    queryDatabase("select Email from StudentProfile where ID=1", function(value) {
//                                                               ^^^^^^^^^^^^^^^^^
      session.send(value);
    });
    session.endDialog();
  } else {
    queryDatabase("select FNAME from StudentProfile where ID=1", function(value) {
//                                                               ^^^^^^^^^^^^^^^^^
      session.send(value);
    });
  }
}).triggerAction({
  matches: 'profile'
})
0 голосов
/ 27 января 2019

Вы можете создать функцию, которая подключается, выполняет запрос, а затем отключается.Это должно выглядеть примерно так:

function execute(query, rowProcessor) {
    connect(function(connection) {
      console.log('Reading rows from the Table...');
      request = new Request(query, function(err, rowCount) {

        if (err) {
          console.log('ERROR in QUERY');
        } else {
          console.log(rowCount + ' rows');
        }
        connection.close();
        request.on('row', rowProcessor);
      });
}

function rowProcessor(columns) {
    columns.forEach(function(column) {
        if (column.value === null) {
            console.log('NULL');
        } else {
            session.send(column.value);
        }
    });
}


if (userMessage.indexOf('Email') >= 0) {
   session.send('Your are looking for your email');
   execute("select Email from StudentProfile where ID=1", rowProcessor);
   // ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...