Я пытаюсь настроить базовый скелет для моего демонстрационного проекта и пишу свою первую программу 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