nodejs api insert into db but sends response 0 - javascript

Whenever I hit this api with sending this
[{"project_id": "knsfviv9",
"coach_id": ""
},
{"project_id": "ovsijiov9",
"coach_id": ""
}]
it inserts into database but it gives response 0 as the result variable remains 0. result variable gets incremented but in res.send it sends 0.
can someone help me with this?
app.post('/api/patc/:id', (req, res) => {
let projectList = req.body;
projectList.forEach(element => {
let data = {
patc_id: "patc-" + randomID(),
college_id: req.params.id,
project_id: element.project_id,
coach_id: element.coach_id,
date: NOW()
};
let sql = "INSERT INTO projects_assigned_to_colleges SET ?";
conn.query(sql, data, (err, results) => {
if (err) throw err;
result.push(results);
});
});
res.send(JSON.stringify({ "status": 200, "error": null, "response": result }));
});

You are trying to execute asynchronous code in forEach which is giving you undesired behavior. Change the code to something like this
app.post("/api/patc/:id", async (req, res) => {
let projectList = req.body;
var result = 0;
const result = await Promise.all(projectList.map(element => {
let data = {
patc_id: "patc-" + randomID(),
college_id: req.params.id,
project_id: element.project_id,
coach_id: element.coach_id,
date: NOW()
};
return new Promise((resolve, reject) => {
let sql = "INSERT INTO projects_assigned_to_colleges SET ?";
conn.query(sql, data, (err, results) => {
if (err) throw err;
resolve(results);
});
});
}));
res.send(JSON.stringify({ status: 200, error: null, response: result }));
});

Related

How to use sql returning id in front-end JavaScript?

I have this request in server.js file.
app.post("/insertRowtoMain", (req, res) => {
const {nodeid, maintenancetype, personnel, process, date} = req.body;
//console.log("description",description)
let insertQuery = `insert into maintenance(nodeid,maintenancetype, personnel, process, date)
values(${nodeid},'${maintenancetype}',${personnel},'${process}', '${date}') returning id`
pool.query(insertQuery, (err, result) => {
if (!err) {
console.log("insertRowtoMain", result.rows);
res.status(200).send(result.rows);
} else {
res.status(404).json(err.message)
console.log("insertRowtoMain error", err.message)
}
})
})
And I am calling this request function in front-end with this code:
const addNewMainTypes = async () => {
try {
await axios.post(`${serverBaseUrl}/insertRowtoMain`, {
nodeid: newMaintenance.nodeid,
maintenancetype: newMaintenance.maintenancetype,
personnel: newMaintenance.personnel,
process: newMaintenance.process,
date: newMaintenance.date,
});
} catch (err) {
throw err;
}
const maintenance = await getMain();
// console.log("main list", maintenanceList);
setMaintenance(maintenance);
const maintenanceList = await getMainTypes();
// console.log("main list", maintenanceList);
setMaintenanceList(maintenanceList);
};
When I insert a new row to this function, I got the returning id in server.js terminal.
How can I use that Id in front-end?
Save the response of the POST request in a variable and access the data property
// Here, "data" will be a variable with the response data
const { data } = await axios.post(`${serverBaseUrl}/insertRowtoMain`, {
nodeid: newMaintenance.nodeid,
maintenancetype: newMaintenance.maintenancetype,
personnel: newMaintenance.personnel,
process: newMaintenance.process,
date: newMaintenance.date,
});
/* Seems like your API is returning an array of objects with "id" property, so, for example... */
// The following should console.log the first element's id of the array
console.log(data[0]?.id);

how to wait to store data in databases with nested loop in NodeJS

i want to fetch data from api and execute for loop to store all response data in mysql database.then again fetch data from api with different request parameter but it does not wait to complete for loop and store data i have tried async/await but noting works
app.get("/api/garudaTx", (req, res) => {
let sql = "SELECT * FROM table_name ORDER BY id ";
let query = conn.query(sql, (err, results) => {
(async function () {
for (let i = 0; i < results.length; i++) {
const element = results[i];
console.log(element.userAddress);
console.log(element.id);
try {
let response = await axios.get(
`https://api.bscscan.com/apimodule=account&action=txlist&address=${element.userAddress}&startblock=1&endblock={blockNo}&sort=asc&apikey=`
);
let last = await (async function () {
console.log(response);
if (response.status != 200 || response.data.result.length == 0) {
let code = response.status.toString();
fs.appendFile("responseError.txt", code + " ", (err) => {
if (err) throw err;
console.log("The lyrics were updated!");
});
fs.appendFile(
"responseError.txt",
element.userAddress + " ",
(err) => {
if (err) throw err;
console.log("The lyrics were updated!");
}
);
}
let body = response.data;
console.log(response.data.result.length);
const promises = [];
for (var index = 0; index < response.data.result.length; index++) {
let data = {
blockNumber: body.result[index].blockNumber,
timeStamp: body.result[index].timeStamp,
hash: body.result[index].hash,
nonce: body.result[index].nonce,
blockHash: body.result[index].blockHash,
from_address: body.result[index].from,
contractAddress: body.result[index].contractAddress,
to_address: body.result[index].to,
value: body.result[index].value,
transactionIndex: body.result[index].transactionIndex,
gas: body.result[index].gas,
gasPrice: body.result[index].gasPrice,
gasUsed: body.result[index].gasUsed,
cumulativeGasUsed: body.result[index].cumulativeGasUsed,
confirmations: body.result[index].confirmations,
};
promises.push(
new Promise((resolve) => {
let sql = "INSERT INTO table_name SET ?";
resolve(
conn.query(sql, data, (err, results) => {
if (err) throw err;
console.log(
JSON.stringify({
status: 200,
error: null,
response: results,
})
);
})
);
})
);
}
await Promise.all(promises);
})();
} catch (err) {
console.log(err);
}
}
})();
});
res.send(JSON.stringify({ status: 200, error: null, response: "success" }));
});
i am executing a for to fetch user details from database then i execute api for each user and saved response data with loop but next api is hitting before saving all data in database it does not wait to complete nested for loop

Make query for every object in json using for or forEach

My problem is, I want to make INSERT query for every object from JSON using some loop, but I almost always got an error "Cannot set headers after they are sent to the client".Can someone help?Tnx
const connection = require('./config');
module.exports.excel = function (req, res) {
var _query = 'INSERT INTO excel (id, first_name, last_name) values ?';
var jsonData = req.body;
var values = [];
function database() {
return new Promise((resolve, reject) => {
jsonData.forEach((value) => {
values.push([value.id, value.first_name, value.last_name]);
connection.query(_query, [values], (error, results) => {
if (error) {
reject(
res.json({
status: false,
message: error.message
}))
} else {
resolve(
res.json({
status: true,
data: results,
message: 'Excel file successfully created in database'
}))
}
});
});
})
}
async function write() {
await database();
}
write();
}
After I got JSON from my Angular 6 front I put req.body into jsonData and try with forEach to put every object("value" in this case) into query and write that into Excel file.
You will have to wrap each query in a Promise and wait for all to complete before sending the response using Promise.all
Not that database() is going to throw when one of the queries fail and you won't have any access to the resolved promises.
const connection = require('./config');
module.exports.excel = function(req, res) {
const _query = 'INSERT INTO excel (id, first_name, last_name) values ?';
const jsonData = req.body;
function database() {
return Promise.all(
jsonData.map(
value =>
new Promise((resolve, reject) => {
const values = [value.id, value.first_name, value.last_name]
connection.query(_query, [values], (error, results) => {
if (error) {
reject(error.message);
return;
}
resolve(results);
});
})
)
);
}
async function write() {
try {
const results = await database();
res.json({
status: true,
data: results,
message: 'Excel file successfully created in database'
});
} catch (e) {
res.json({
status: false,
message: e.message
});
}
}
write();
};

Node js returning values from function

I live in the PHP world but I am attempting to build out a REST Api using Node.
I have been stuck all day of trying to return an array of results from a for loop. Basically I am passing an array of field_name:field_value. I want to push the result from the update into an array to return. I can get it to log in the console but no further.
Here is a sample post json data
{
"first_name":"Jeff",
"phone":"4855555555"
}
Here is the function and loop
function UpdateKey(user_id, key, value, cb) {
connection.query('UPDATE users SET ' + key + ' = ? WHERE id = ? LIMIT 1', [value, user_id], function(err, results) {
if (err) {
callback = key + " update failed.";
} else {
callback = key + " was updated.";
}
cb(callback);
});
}
for (myKey in post_data) {
UpdateKey(user_id, myKey, post_data[myKey], function(id) {
console.log(id);
});
}
res.send(JSON.stringify({ "status": 200, "error": "", "response": my_results_here }));
I have been researching async but not sure the best route here. Any help would be great!
You could collect all results in an array and send that when the arrays size equals the keys size:
const keys = Object.keys(post_data);
const response = [];
for(const myKey of keys) {
UpdateKey(user_id, myKey, post_data[myKey], function(id) {
response.push(id);
if(keys.length === response.length) {
res.send(JSON.stringify({
status: 200,
error: "",
response
}));
}
});
}
The solution You want:
const updateUserField = (userId, field, value) => {
return Promise((resolve) => {
const query = 'UPDATE users SET ' + field + ' = ? WHERE id = ?';
const data = [value, userId];
connection.query(query, data, (error) => {
if (error) return resolve(field + ' update failed');
resolve(field + ' was updated');
});
});
};
router.post('/user/:id', async (req, res) => {
const userId = req.params.id;
const data = req.body;
const response = [];
for (const field in data) {
response.push(
await updateUserField(userId, field, data[field])
);
}
res.status(200).send({
response
});
});
or in parallel:
router.post('/user/:id', async (req, res) => {
const userId = req.params.id;
const data = req.body;
const response = await Promise.all(
Object
.keys(data)
.map(field => updateUserField(userId, field, data[field]))
);
res.status(200).send({
response
});
});
Correct solution
As I understand You want to get post data and update record in users table.
So why not just do it in one query?
Try this way:
const updateUser = (userId, data) => {
return Promise((resolve, reject) => {
const query = 'UPDATE users SET ? WHERE id = ?';
connection.query(query, [data, userId], (error) => {
if (error) return reject(error);
resolve();
});
});
};
router.post('/user/:id', async (req, res) => {
try {
const userId = req.params.id;
const data = req.body;
await updateUser(userId, data);
res.status(200).send({
message: 'User account successfully updated'
})
}
catch (error) {
console.error(error);
res.status(500).send({
message: 'Failed update user account'
});
}
});
But better think about using ORM i.e. Sequelize for security, validation and etc features that eases dev's life.

node js mssql output parameter returns null value

I am trying to insert details into db and after that i need to get out put parameter value but after implementing the below code i was successfully inserts into db but output parameter has null value.
I check in db code works fine but in node js i see that there is null value.
I am using mssql package
Below is code..
sql.close();
sql.connect(config, function (err) {
if (err) console.log(err);
//create Request object
var request = new sql.Request();
console.log(EXCEL_ROWS);
request.input('p_Flag', sql.VarChar, UpdateQualityExcel_Flag)
request.input('p_ProjectCode', sql.NVarChar, EXCEL_ROWS.PROJECT_CODE);
request.input('p_ActivityId',sql.INT,EXCEL_ROWS.ACTIVITY_ID);
request.input('p_ActivityName', sql.VarChar, EXCEL_ROWS.ACTIVITY_NAME);
request.output('po_Message',sql.VarChar)
request.output('po_ActivityClosed',sql.INT)
// query to the database and get the records
request.execute("[dbo].[ARA_SP_ACTION_QualityExcelUpdate]").then(function(recordSet) {
if (recordSet == null || recordSet.length === 0)
return;
console.log(request.parameters.po_ActivityClosed.value)
}).catch(function (err) {
console.log(err);
});
output:
null
export const updateRequerimientoById = async (req, res) => {
const { Id_Cliente, Id_CentroComercial, Descripcion, Situacion } = req.body;
if ( Descripcion == null ) {
return res.status(400).json({ msg: "Solicitud incorrecta. Por favor llena todos los campos" });
}
try {
const pool = await getConnection();
await pool.request()
.input("Id_Requerimiento", sql.Int, req.params.id_requerimiento)
.input("Id_Cliente", sql.Int, Id_Cliente)
.input("Id_CentroComercial", sql.Int, Id_CentroComercial)
.input("Descripcion", sql.Text, Descripcion)
.input("Situacion", sql.Int, Situacion)
.output("Id_Resultado",sql.Int)
.output("Result_Codigo",sql.Int)
.output("Result_Mensaje",sql.VarChar(100))
.execute(requerimientoquerys.updateRequerimientoById, function(err, recordsets, returnValue) {
const summary = {
Result: recordsets.output,
Record: recordsets.output["Result_Codigo"] === 200 ? req.body : {}
};
res.json(summary);
});
} catch (error) {
res.status(500);
res.send(error.message);
}
};
{
"Result": {
"Id_Resultado": 12,
"Result_Codigo": 200,
"Result_Mensaje": "ActualizaciĆ³n realizada con exito."
},
"Record": {
"Id_Cliente": 1,
"Id_CentroComercial": 1,
"Descripcion": "POSTMAN POSTMAN 10 EXITOS",
"Situacion": 0
}
}

Categories

Resources