Express API - select one id from database - api

i want to know how can i realize passing parameter to Model. I have 3 file server.js , controllers/news.js and models/news.js
Server.js
const newsController = require('./controllers/news');
server.get('/newsAll', newsController.all);
server.post('/getOneNews', (req, res) => {
db.get().query(`SELECT * FROM news WHERE id = ?`, [ req.body.id ],
(err, result, fields) => {
if (err) console.log('error SELECT one row', err);
});
});
controller/news.js
const newsModule = require('../models/news');
exports.all = (req, res) => {
newsModule.all((err, rows) => {
if (err) {
console.error(err);
return res.sendStatus(500);
}
res.send(rows);
});
};
models/news.js
const db = require('../db');
exports.all = (done) => {
db.get().query(`SELECT * FROM news ORDER BY id`, (err, rows) => {
if (err) {
console.log('error SELECT * FROM news MYSQL', err);
throw err;
}
done(err, rows);
});
};
All about method all i understood , but i want to know how can i passing [ req.body.id ] (<- from front-end) this parametr to Model for accepting ONE news from database . Whithout parameters it is very easy.

All you need is to do is grab the id from the req.params object and then set your endpoint to accept that params value.
// Server.js
server.get('/getOneNews/:id', (req, res) => {
db.get().query(`SELECT * FROM news WHERE id = ?`, [ req.params.id ],
(err, result, fields) => {
if (err) console.log('error SELECT one row', err);
});
});
Hope this helps!

Related

update query in sqlite failed

I send my object by post request with postman then in the backend with node js recive it and update my table but it return sqlerror on string in object and no problem on integer !
1 - my obj in postman => {
"id" : 3,
"controlsCode":123456,
"controlsName" : "hamed"
}
2 - my code in node =>
async editControls(req, res) {
try {
const { id, controlsCode, controlsName } = req.body;
const query = `update controls set controlCode=${controlsCode} , controlName=${controlsName} where id =${id}`;
await sequelize
.query(query)
.then((item) =>
this.response({ res, message: "ok", data: controlsCode })
)
.catch((error) => console.log(error.message));
} catch (error) {
console.log(error.message);
}
}
3-error in node js =>
SQLITE_ERROR: no such column: hamed
You need single quotes around the string literal:
try {
const { id, controlsCode, controlsName } = req.body;
const query = `update controls set controlCode=${controlsCode} , controlName='${controlsName}' where id =${id}`;
await sequelize
.query(query)
.then((item) =>
this.response({ res, message: "ok", data: controlsCode })
)
.catch((error) => console.log(error.message));
} catch (error) {
console.log(error.message);
}

Result is not Defined "Error" in server logs for a GET request to DB

router.get('/', rejectUnauthenticated, (req, res) => {
console.log('Ticket Info GET');
const sqlQuery = `SELECT "question","department","priority" FROM "question_table";`;
// const sqlParams=[req.params.id]
// console.log('Log for sql Params', sqlParams);
pool.query(sqlQuery)
.then((dbResponse) => {
console.log('Ticket Details GET',dbResponse);
res.send(dbResponse.rows);
console.log('Ticket Details GET');
})
.catch((err) => {
console.log('ERROR: Get all videos', err);
res.sendStatus(500)
})
});

get logged in ID from jwt so that only logged in user can see particular data in nodejs

I am using nodejs, jwt and mysql.
I want the current logged in user ID soo that I can show the data respective to it.
This is my code where SQL logic is written and here I am expecting to get a current user ID.
const pool = require('../../dbconfig/dbconfig');
module.exports = {
getProfile : (callBack) => {
var sql = 'SELECT name, shopStatus, phone, shopaddress.shopNo, shopaddress.complex, shopaddress.landmark, shopaddress.street, shopaddress.area, shopaddress.city FROM shop INNER JOIN shopaddress ON shop.id = shopaddress.shop_id WHERE shop.id = ?'
var insertSql = [ /* how can i get ID here.. */ ]
pool.query(sql, insertSql, (err, results, fields) => {
if(err) {
return callBack(err)
}
return callBack(null, results)
})
}
}
this happens to be jwt middleware code
const jwt = require('jsonwebtoken')
const config = require('../../config')
module.exports = {
isAuth: (req, res, next) => {
let token = req.get("authorization");
if (token) {
// Remove Bearer from string
token = token.slice(7);
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.json({
status: 'error',
message: "Invalid Token..."
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.json({
status: 'error',
message: "Access Denied! Unauthorized User"
});
}
}
};
and this is controller
const shopService = require('./shop.service')
module.exports = {
shopProfile : (req, res) => {
shopService.getProfile((err, results) => {
if(err){
return res.status(500).json({
status : 'error',
error : err,
message : 'Database connection error'
})
}
return res.status(200).json({
status:'success',
data : results
})
})
}
}

Sqlite3 returning empty array with GET request in Express

I am trying to make a get request to an sqlite3 table, using Express, based on input from a form. The fetch request works and so does the db.all, but I receive a response as an empty array from rows. I tried req.query and req.params already. Not sure where the error is.
//server.js
app.get('/names/state', (req, res, next) => {
const stateValue = req.query.state;
db.all(`SELECT name FROM states WHERE name=$stateVal`,
{
$stateVal: stateValue
},
(err, rows) => {
res.send({rows:rows});
})
});
//script.js
const fetchOneBtn = (e) => {
e.preventDefault();
const stateVal = stateInputValue.value;
fetch(`/names/state?state=${stateVal}`)
.then(response =>{
if(response.ok){
return response.json();
}
}).then(names => {
console.log(names);
})
};
You can change your code in your backend with this code below:
app.get('/names/state', (req, res, next) => {
const stateValue = req.query.state;
var query = "SELECT name FROM states WHERE name = " + stateValue;
db.all(query, (err, rows) => {
if(err) {
console.log(err);
res.status(500).send(err);
}else {
res.send({rows});
}
})
});
Now, for your frontend, you can change with the code below:
const fetchOneBtn = async (e) => {
e.preventDefault();
const stateVal = stateInputValue.value;
try {
const response = await fetch(`/names/state?state=${stateVal}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
});
console.log(await response.json());
return await response.json();
} catch(ex) {
console.log(ex);
}
};
I hope it can help you.

Send single response after multiple updates

I have an array of items that I am passing to an API endpoint (using Sequelize as my ORM). I'm trying to iterate over each item and update it, however I'm getting a Unhandled rejection Error: Can't set headers after they are sent.
stepsController.put = (req, res) => {
const { steps } = req.body;
// Steps is an array of objects that I want to update...
steps.map(step => {
Step.findOne({ where: { id: step.id } })
.then(savedStep =>
savedStep
.update({
order: step.order,
})
.then(success => res.status(200).send(success))
.catch(error => res.send(error))
)
.then(ok => res.status(200).send(ok))
.catch(err => res.send(err));
});
};
I believe this is because it's sending the response for each item. Sequelize's update method is a promise. How can I iterate over all of the items and make sure all of the items are updated before sending a single successful response?
There are three ways you can do
Promise.all
Co
Async Await
1) Here it is , you can use Promise.all :
stepsController.put = (req, res) => {
const { steps } = req.body;
// Steps is an array of objects that I want to update...
Promise.all(steps.map(step => {
return Step.findOne({ where: { id: step.id } }).then(savedStep =>
return savedStep.update({
order: step.order,
})
.catch(error => error)
).catch(err => err)
}))
.then(ok => res.status(200).send(ok))
.catch(err => res.send(err));
};
2) Another way is to use co :
const co = require('co');
stepsController.put = co.wrap(function* (req, res) => {
try {
const { steps } = req.body;
// Steps is an array of objects that I want to update...
for(let i=0;i<steps.length ; i++) {
let savedStep = yield Step.findOne({ where: { id: steps[i].id } });
if(savedStep)
yield savedStep.update({ order: steps[i].order});
}
res.status(200).send();
}
catch(err){
res.send(err);
}
});
3) If you’re using Node 8.0+ , there is no need of any package you can directly use async await :
stepsController.put = async(req, res) => {
try {
const { steps } = req.body;
// Steps is an array of objects that I want to update...
for(let i=0;i<steps.length ; i++) {
let savedStep = await Step.findOne({ where: { id: steps[i].id } });
if(savedStep)
await savedStep.update({ order: steps[i].order});
}
res.status(200).send();
}
catch(err){
res.send(err);
}
};