use a field as a parameter for nodejs express - node.js

I am curious if it is possible to use a fieldname as a parameter for express.
My sql statement is as follows:
const INSERT_VALUE_VIA_FIELD = "UPDATE businesses set ? = ? where userId = ?";
...
router.post("/update", async (req, res) => {
const { field, value, userId } = req.body;
connection.query(
INSERT_VALUE_VIA_FIELD,
[field, value, userId],
async (error, rows) => {
res.set("Access-Control-Allow-Origin", "*");
if (error) {
res.json({ error: error.sqlMessage });
req.on("end", () => {
res.statusCode = 400;
res.end("Bad Request");
});
} else {
res.json({ field, value, userId });
req.on("end", () => {
res.statusCode = 200;
res.end("OK post");
});
}
}
);
});
I pass in the properties as follows:
{
"field": "name",
"value":"test",
"userId": 23
}
in which i expect the mysql statement to run as:
"UPDATE businesses set name = "test" where userId = 23";
When i run this via postman, i get the following error:
"error": "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('name') = 'test' where userId = 23' at line 1"
Any ideas?

So it isnt the most feasible answer, but it works. I have substituted the string with back ticks as suggested by Mostafa and passing in the field param within the statement as so:
router.post("/update", async (req, res) => {
const { field, value, userId } = req.body;
connection.query(
`UPDATE businesses set ${field} = ? where userId = ?`,
[value, userId],
async (error, rows) => {
res.set("Access-Control-Allow-Origin", "*");
if (error) {
res.json({ error: error.sqlMessage });
req.on("end", () => {
res.statusCode = 400;
res.end("Bad Request");
});
} else {
res.json({ field, value, userId });
req.on("end", () => {
res.statusCode = 200;
res.end("OK post");
});
}
}
);
});

Related

I need to Update one record in mongodb?

router.patch('/edit/:id', async (req, res) => {
try {
let id = req.params.id;
let updateData = req.body;
const result = await Category.updateOne(id,updateData);
if(result) {
res.status(200).send({
result: result
});
}
}
catch (err) {
for (field in ex.errors) {
res.status(500).send(ex.errors[field].message);
}
}
})
This is my code but its not Working data not changed in records when i call this function

GET endpoint returns a 404

I am trying to retrieve specific user data from my Postgres DB.
This code, which retrievs all user data works:
app.get("/employees", async (req, res) => {
try {
const allEmployees = await pool.query("SELECT * FROM employees");
res.json(allEmployees.rows);
} catch (err) {
console.error(err.message);
}
});
But this code meant to retrieve one user doesn't. It returns a 404 on Postman.
app.get("/employees/:id", async (req, res) => {
try {
const { id } = req.params;
const oneEmployee = await pool.query("SELECT * FROM employees WHERE emp_id = $1", [
id
]);
res.json(oneEmployee.rows[0]);
} catch (err) {
console.error(err.message);
}
});
I don't seem to figure out what the problem is.
#AnujPancholi an update. I used the node-postgres queries documentation and changed my code as follows:
app.get("/employees/:emp_id", async (req,res) => {
const query = {
// give the query a unique name
name: 'fetch-user',
text: 'SELECT * FROM employees WHERE emp_id = $1'
}
query.values = [req.params.emp_id];
// callback
await pool.query(query, (err, response) => {
if (err) {
console.log(err.stack);
} else {
res.json(response.rows);
}
});
});
then on Postman my endpoint to a GET route
http://localhost:3000/employees/4
I did not enter any values on the params section. Thanks for pointing me in the right direction, especially on the Postman part.

How can I get list record from SQL Server in NodeJS

I start to develop a simple web application with NodeJS. and when I try to get a list record from SQL Server to show on the list page but somehow it's not working.
Here is the code :
const express = require("express");
const bodyParser = require("body-parser");
const sql = require("mssql");
const DBUtils = require("./DBUtils");
const app = express();
app.get("/all", (req, res, next) => {
let mypromise = new Promise((reso, rej) => {
let nameList = DBUtils.getNameList(sql);
if (nameList !== null || typeof nameList !== "undefined") {
reso(nameList);
} else {
rej("Error");
}
})
.then((result) => {
res.send(result);
})
.catch((err) => {
console.log(err);
});
});
app.get("/", (req, res, next) => {
console.log("the / route");
res.send("<h1>Hello to NodeJS</h1>");
});
app.listen(5003);
My DBUtils
const config = {
user: "sa",
password: "123",
server: "DESKTOP-7KGJI7L", // You can use 'localhost\\instance' to connect to named instance
database: "java",
options: {
encrypt: false,
},
};
const getNameList = (sql) => {
let nameList = "";
let errorString = "";
// Create connection
sql.connect(config, function (err) {
// Err
if (err) {
console.log(err);
}
// Create Request object
let sqlRequest = new sql.Request();
// QueryString
let queryString = `select * from NAME`;
// Run the query
sqlRequest.query(queryString, (err, data) => {
if (err) console.log(err);
//console.log(data); //data.recordset(array)[index].name
data.recordset.forEach((el) => {
nameList += `<li>${el.name}</li>`;
});
return nameList;
});
});
};
exports.getNameList = getNameList;
I pretty sure something wrong in Promise line but don't know how to fix it. Any suggest?
I think you are a newbie in Nodejs You made a common mistake. You did not use promise pattern correctly. Also, no need to pass next callback unless required.
Change getNameList as below :
const getNameList = (sql) => {
let nameList = "";
let errorString = "";
// Create connection
return new Promise (function(resolve,reject) {
sql.connect(config, function (err) {
// Err
if (err) {
console.log(err);
reject(err)
}
// Create Request object
let sqlRequest = new sql.Request();
// QueryString
let queryString = `select * from NAME`;
// Run the query
sqlRequest.query(queryString, (err, data) => {
if (err) {console.log(err)
reject(err)
}
//console.log(data); //data.recordset(array)[index].name
data.recordset.forEach((el) => {
nameList += `<li>${el.name}</li>`;
});
resolve(nameList);
});
});
})
};
Change app.get("/all") as below:
app.get("/all", (req, res) => {
DBUtils.getNameList(sql).then(function(list) {
res.status(200).send(list)
}).catch(function(err) { //handle error here
res.status(500)
})
})
Moreover, learn how to use promises and async-await.
Use appropriate body-parser as per requirement ie json, text etc.
Learn how and when to use next

nodejs express postgresql create use in db user table

What is a practical way to check if a user is already in the db before trying to insert the information for a "new user"
Here is my get user by id and insert function:
const getUserById = (request, response) => {
const id = parseInt(request.params.attuid)
pg.query('SELECT * FROM geodate.users WHERE attuid = $1', [attuid], (err, res) => {
if (err) {
return next(err)
}
response.status(200).json(results.rows)
})
}
const createUser = (request, response) => {
const attuid = request.body[0].attuid
pg.query('INSERT INTO geodata.users (attuid, num_queries,created_date,modified_date) VALUES ($1,$2,$3,$4) RETURNING *', [attuid, 0, moment(new Date()), moment(new Date())], (error, results) => {
if (error) {
throw error
}
response.status(201).send(`User added with ID: ${results.rows[0].attuid}`)
})
}
Thanks
rf guy,
Nice shades. First select the user from the geodata.users table. If the user exists, you should not add the user. I don't use pg to query postgres, so I really don't know how it works, but you should be able to do this:
const createUser = (request, response) => { const attuid = request.body[0].attuid
pg.query('SELECT * FROM geodate.users WHERE attuid = $1', [attuid], (err, res)=> {
if (err) {
return next(err)
}
if(results.rows > 0)
{
pg.query('INSERT INTO geodata.users (attuid, num_queries,created_date,modified_date) VALUES ($1,$2,$3,$4) RETURNING
*', [attuid, 0, moment(new Date()), moment(new Date())], (error, results) => {
if (error) {
throw error
}
response.status(201).send(`User added with ID: ${results.rows[0].attuid}`)
})
}
else{
response.status(200).json({"message": "Ha! you are already in the db, silly"})
} }) }

firebase aync await getting null object in try catch

I am working on firebase api for realtime database, I am using async await, but it is not working for that i have used try catch in node js, I can see i am getting status 0, so it invokes catch, but in catch i am getting error as null object, can anyone please help me why i am not getting proper error in that ? even my try code is correct still it invokes catch, here i have added my whole code, can anyone please look in my code, and help me to resolve this error ? i am getting this response,
Response :
{"status":0,"data":{}}
API :
export const check_await = functions.https.onRequest(async (req, res) => {
try {
if (req.method === 'POST') {
const body_data = req.body;
const db = admin.database();
const org_id = body_data.company_id;
const highfive_id = body_data.highfive_id;
const ref = db.ref("organizations/" + org_id + "/highfive/" + highfive_id);
const snapshot = await ref.on("value");
const data = snapshot.val();
cors(req, res, () => { return res.send({ 'status': 1, 'data': data, 'msg': 'High five feed record get successfully' }); });
} else {
cors(req, res, () => { return res.send({ 'status': 0, 'msg': "Only POST method is allowed" }); });
}
} catch (error) {
cors(req, res, () => { return res.send({ 'status': 0, 'data': error }); });
}
});
Finally i resolved the issue, i need to use once instead of on, here is my full code of it,
export const check_await = functions.https.onRequest(async (req, res) => {
try {
if (req.method === 'POST') {
const body_data = req.body;
const db = admin.database();
const org_id = body_data.company_id;
const highfive_id = body_data.highfive_id;
const ref = db.ref("organizations/" + org_id + "/highfive/" + highfive_id);
const snapshot = await ref.once("value");
const data = snapshot.val();
cors(req, res, () => { return res.send({ 'status': 1, 'data': data, 'msg': 'High five feed record get successfully' }); });
} else {
cors(req, res, () => { return res.send({ 'status': 0, 'msg': "Only POST method is allowed" }); });
}
} catch (error) {
cors(req, res, () => { return res.send({ 'status': 0, 'data': error.message }); });
}
});

Resources