I am creating a REST API service using Azure Function in nodeJs. The function is reading some data from Azure SQL and I want it to be returned. I am using tedious package to connect to Azure SQL Database.
const { Connection, Request } = require("tedious");
var data = [];
console.log("0." + data);
const config = {
authentication: {
options: {
userName: "------", // update me
password: "--------" // update me
},
type: "default"
},
server: "----.database.windows.net", // update me
options: {
database: "---", //update me
encrypt: true
}
};
module.exports = async function (context, req, resp) {
const connection = new Connection(config);
context.bindings.response = { status: 201, body: {"time": new Date().getUTCMinutes(), "data": data} };
connection.on("connect", err => {
if (err) {
console.error(err.message);
} else {
queryDatabase(context);
}
});
connection.connect();
//context.bindings.response = { status: 201, body: JSON.stringify(data) };
function queryDatabase(context) {
console.log("Reading rows from the Table...");
// Read all rows from table
const request = new Request(
`SELECT FirstName, LastName FROM Persons`,
(err, rowCount, data) => {
if (err ) {
console.error(err.message);
} else {
console.log(`${rowCount} row(s) returned`);
}
}
);
request.on("row", columns => {
var row = {};
columns.forEach(column => {
row[column.metadata.colName] = column.value;
console.log("%s\t%s", column.metadata.colName, column.value);
data.push(row);
});
});
connection.execSql(request);
}
}
I can read data from Azure SQL Database and the console.log
is printing data in the console.
console.log("%s\t%s", column.metadata.colName, column.value);
But while I am trying to bind the data to response, it always shows blank.
{
"time": 52,
"data": []
}
How and where to bind the context.bindings.response
?