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"})
} }) }
Related
I've an issue while i'm trying to delete a driver from mySQL db.
Calling my function and passing mapped id (it's working):
<button id="deleteRent" onClick={DeleteVehicles.bind(vehicle.id)}>Delete</button>
Here is my react code:
const DeleteVehicles = (CarId) => {
Axios.delete(`http://localhost:3001/vehicleDelete/${CarId}`)
.then((response) => {
if (response) {
console.log(response)
alert("Sikeres Törlés")
navigate("/admin");
}
else {
console.log("törlési hiba")
}
})
}
and here is my node express request:
app.delete('/vehicleDelete/:CarId'), async (req, res) => {
db.query("DELETE FROM products WHERE id = ?", req.params.CarId,
(err, result) => {
console.log(err)
console.log(result)
if (result) {
res.send(result);
}
})
}
any idea?
axios should be lowercased:
axios.delete(`http://localhost:3001/vehicleDelete/${CarId}`)
Be careful with the closing parentheses on the express code:
app.delete('/vehicleDelete/:CarId', async (req, res) => {
db.query("DELETE FROM products WHERE id = ?", req.params.CarId, (err, result) => {
if (err) return res.status(500).send('Error')
res.status(200).send(result);
})
})
You should run this:
app.delete('/vehicleDelete/:CarId'), (req, res) => {
// make sure your are getting CarId that exists
// and then you delete it
db.query(`DELETE FROM products WHERE id = ${req.params.CarId}`,
(err, result) => {
console.log(err)
console.log(result)
if (result) {
res.send(result);
}
})
}
Also, you don't need to add async as your not using await for the query. The result gives you an object that might look like this:
{
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
Now, when you say you receive the 404 status code, it means that you don't have the route on which the request is made. So, http://localhost:3001/vehicleDelete/${CarId} you need to register the route properly at the server.
You should add the catch blocks with Promises, it is recommended practice.
const DeleteVehicles = (CarId) => {
Axios.delete(`http://localhost:3001/vehicleDelete/${CarId}`)
.then((response) => {
if (response) {
console.log(response)
alert("Sikeres Törlés")
navigate("/admin");
}
else {
console.log("törlési hiba")
}
}).catch(console.log);
}
I need to run two queries against different servers / databases, merge the result sets and return them in the same response.
const express = require('express')
const app = express()
const cors = require('cors')
const sql = require('mssql')
app.use(cors())
app.get('/api/', (req, res) => {
sql.connect(config_03, (err) => {
if (err)
console.log(err)
let sqlRequest = new sql.Request()
let sqlQuery = "select foo, bar from foobar"
sqlRequest.query(sqlQuery, (err, data) => {
if (err) {
console.log(err)
} else {
/*save first response*/
}
sql.close()
})
})
sql.connect(config_01, (err) => {
if (err)
console.log(err)
let sqlRequest = new sql.Request()
let sqlQuery = "select foo, bar from foobar"
sqlRequest.query(sqlQuery, (err, data) => {
if (err) {
console.log(err)
} else {
/*save second response*/
}
sql.close()
})
})
res.send(/*both responses*/)
})
const config_03 = {
server: 'server01',
/**/
}
const config_01 = {
server: 'server01',
/**/
}
const webserver = app.listen(5000, () => {
console.log('node running')
})
With this code the second result set is always empty. What should I change so that both queries run and the result sets are merged and returned together ?
Have you tried something like this?
app.get('/api/', (req, res) => {
var output = [];
sql.connect(config_03, (err) => {
if (err)
console.log(err)
let sqlRequest = new sql.Request()
let sqlQuery = "select foo, bar from foobar"
sqlRequest.query(sqlQuery, (err, data) => {
if (err) {
console.log(err)
} else {
output.push(data);
}
sql.close()
})
})
sql.connect(config_01, (err) => {
if (err)
console.log(err)
let sqlRequest = new sql.Request()
let sqlQuery = "select foo, bar from foobar"
sqlRequest.query(sqlQuery, (err, data) => {
if (err) {
console.log(err)
} else {
output.push(data);
}
sql.close()
})
})
res.send(output);
})
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.
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
Im trying to build a rest api, fetching a nested mysql queries.
When i fetch the first query, this return a array, then with this array i need to fetch data with another query for each value through a array.map
when the script running, always log a empty array, i think must be cause of promises. any help please?
//this the mysql queries
const getTournaments = 'SELECT ID FROM wp_posts WHERE post_type = "tournament"'
const getTournamentGame = 'SELECT meta_value FROM wp_postmeta WHERE meta_key = "tournament_game" AND post_id = ?'
async function fetchType(id){
return new Promise ((res, rej) => {
try{
pool.query(getTournamentGame, [id], (err, rows) => {
if (err) {
return rej(err)
}else {
return res(rows[0].meta_value)
}
})
} catch(err){
console.log(err)
}
})
}
async function mapeado(array) {
return new Promise (async (resolve,rej) => {
try{
var arr = []
array.map((item) => {
fetchType(item.ID).then((res) => {
var tourData = {
id: item.ID,
type: res
}
return tourData
}).then((data) => {
arr.push(data)
})
})
return resolve(arr)
} catch(err) {
console.log(err)
}
})
}
//making rest api
app.get('/tournaments', async (req, res) => {
pool.query(getTournaments, (err, rows) => {
mapeado(rows).then(console.log)
})
})