I have coded a program when I click on run and execute the program, it will automatically update to my database, however I am not sure why my device id that I took is not the same as the one from minut, is there a way to fix this issue?
My Index.js
const { default:axios } = require("axios");
const { Connection, Request } = require("tedious");
const dbConfig = {
authentication: {
options: {
userName: "learning-space-analytics", // update me
password: "***" // update me
},
type: "default"
},
server: "learning-space-analytics.database.windows.net", // update me
options: {
database: "learning-space-analytics", //update me
encrypt: true
}
};
const connection = new Connection(dbConfig);
module.exports = async function (context, req) {
const tokenRes = await axios.post("https://api.minut.com/v7/oauth/token", {
"grant_type": "refresh_token",
"client_id": "",
"client_secret": "",
"refresh_token": ""
});
const { access_token } = await tokenRes.data;
const sensorRes = await axios.get("https://api.minut.com/v7/devices", {
headers: {
"Authorization": `Bearer ${access_token}`
}
});
const { devices } = await sensorRes.data;
const sqlCmds = [];
for (const device in devices) {
const { device_id, active, offline, latest_sensor_values } = devices[device];
const { temperature, sound, humidity } = latest_sensor_values;
if (active && !offline) {
sqlCmds.push(`INSERT INTO [learning-space-analytics].[dbo].[SensorReading] VALUES (${new Date(temperature.time).getSeconds()}, ${sound.value}, 0, ${humidity.value}, ${temperature.value}, ${device_id}, "admin1", ${Date.now()})`)
};
};
connection.on("connect", err => {
if (err) {
console.error(err.message);
} else {
//for (const cmd in sqlCmds) {
queryDatabase(sqlCmds[0]);
// }
}
});
connection.connect();
context.res = {
// status: 200, /* Defaults to 200 */
body: {
"status": "ok"
}
};
}
function queryDatabase(cmd) {
const request = new Request(
cmd,
(err, rowCount) => {
if (err) {
console.error(err.message);
} else {
console.log(`${rowCount} row(s) returned`);
}
}
);
request.on("row", columns => {
columns.forEach(column => {
console.log("%s\t%s", column.metadata.colName, column.value);
});
});
connection.execSql(request);
}
When I click on the run and execute the azure it will show an error: Incorrect syntax near 'a9dff4fbc6f86a88d4c1ab'.(the device id) The correct device id should be 61a9dff4fbc6f86a88d4c1ab, the 61 is missing tho, how to fix that issue?
CodePudding user response: