如何重构此node.js代码,以避免重复

时间:2019-01-27 16:04:12

标签: javascript node.js azure-bot-service

我试图为我的演示项目设置基础框架,并编写我的第一个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 :(得分:0)

您可以创建一个函数,该函数可以连接,运行查询然后断开连接。它看起来应该像这样:

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);
   // ...

答案 1 :(得分:0)

  

我厌倦了下面的方法,但是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'
})