router.get("/stocks/symbols", function (req, res, next) {
req.db
.from("stocks")
.select("name","symbol","industry")
.modify(function(queryBuilder) {
if (req.query.param) {
queryBuilder.where('industry',req.query.param);
}
})
.where('timestamp', '=', '2020-03-24T00:00:00Z')
.then((rows) => {
res.json(rows)
})
.catch((err) => {
console.log(err)
res.json({ Error: false, Message: "Error in MySQL query" })
})
})
I'm trying to make such a functionality to use querystring.
At the moment this runs without error but doesn't do anything.
Whether I put ?industry=h or anything after the route, it returns the same data.
There was an example I followed, but for some reason its not working.
What else am i missing?
router.get("/stocks/symbols/:industry", function (req, res, next) {
req.db
.from("stocks")
.select("name","symbol","industry")
.where('timestamp', '=', '2020-03-24T00:00:00Z')
.where("industry", "like", `%${req.params.industry}%`)
.then((rows) => {
res.json({ Error: false, Message: "Success", Cities: rows })
})
.catch((err) => {
console.log(err)
res.json({ Error: true, Message: "Error in MySQL query" })
})
})
This does similar job that i want to do but it doesn't use the querystring.
You need to apply the correct query parameter - in your code you use query.param meaning that your url would need to contain /stocks/symbols?param=tbd
If you're expecting industry as a query-param, you need to change it to:
.modify(function(queryBuilder) {
if (req.query.industry) {
queryBuilder.where('industry',req.query.industry);
}
})
Related
I created 3 functions: findOne, create and update. Respectively the methods are GET, POST, PUT.
I changed my API path, it used to be /api/users/:id, now it's /api/users/:sub.
routes.js:
module.exports = app => {
const users = require("../controllers/user.controller.js");
const router = require("express").Router();
// Create a new User
router.post("/", users.create);
// Retrieve a single User with sub
router.get("/:sub", users.findOne);
// Update a User with sub
router.put("/:sub", users.update);
// Delete a User with sub
router.delete("/:sub", users.delete);
app.use('/api/users', router);
};
controller.js:
// Save User in the database
User.create(user)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the Users."
});
});
};
// Find a single User with an id and sub
exports.findOne = (req, res) => {
const sub = req.params.sub;
User.findOne({sub})
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message: "Error retrieving User with id=" +sub
});
});
};
// Update a User by the sub in the request
exports.update = (req, res) => {
const sub = req.params.sub;
User.update(req.body, {
where: { sub }
})
.then(num => {
if (sub) {
res.send({
message: "User was updated successfully."
});
} else {
res.send({
message: `Cannot update User with sub=. Maybe User was not found or req.body is empty!`
});
}
})
.catch(err => {
res.status(500).send({
message: "Error updating User with sub="
});
});
};
What I wanted to do was: check if the user_id provided by the authentication provider was present in my database.
If yes, update user data with that user_id.
If not, create a new user record
This is the front-end part involved:
//INFO SAVE AND UPDATE CONDITION
const userExist = InfoDataService.get(data.sub)
.then((response) => {
console.log('find', response.data);
return true;
});
if ( userExist ) {
InfoDataService.create(data)
.then((response) => {
console.log('create', response.data);
setInfo({
id: response.data.id,
sub: response.data.sub,
email: response.data.email,
firstname: response.data.firstname,
lastname: response.data.lastname,
});
})
} else {
InfoDataService.update(sub, data)
.then((response) => {
console.log(response.data);
})
.catch((e) => {
console.error(e);
});
}
};
I thought userInDatabase could only give true or false, so I used it as an argument in the if statement. It does not work and just updates.
If you need any other information, please ask, I have just started and I hope I have given the necessary info.
EDIT
Through findOne I can find the entire object in my database, but I thought that putting the function as an if condition could give me true if it found the object with its sub; false if he found nothing.
This is not the case, in fact in the code I just updated, although findOne works correctly, it continues to execute always and only create.
router.get("/stocks/symbols/:industry", function (req, res, next) {
req.db
.from("stocks")
.select("name","symbol","industry")
.where('timestamp', '=', '2020-03-24T00:00:00Z')
.where("industry", "like", '%h%')
.then((rows) => {
res.json({ Error: false, Message: "Success", Cities: rows })
})
.catch((err) => {
console.log(err)
res.json({ Error: true, Message: "Error in MySQL query" })
})
})
Above is the code for getting stocks with industry that includes h in it.
Such as Healt'h' Care and Information Tec'h'nology
What I'm trying to do is instead of using '%h%' to get the fixed response, use req.params.industry
What do i have to do to fix it?
I'm unable to understand what actually is wrong with my code. But I know there is a problem in how I'm implementing Promise. As Shipment.findAll() returns a Promise, and I'm creating a promise again for my router to consume.
Then why createShipment is working fine, and getAllShipments is not working.
Controller for Shipment
const Worker = require ('../models').Worker;
const Shipment = require ('../models').Shipment;
function createShipment (shipmentName, shipmentStatus) {
return new Promise ((resolve, reject) => {
Shipment.create({name: shipmentName, status: shipmentStatus})
.then (shipment => resolve(shipment))
.catch (error => reject(error));
});
}
function getAllShipments () {
return new Promise ((resolve, reject) => {
Shipment.findAll()
.then(allShipments => {
console.log(allShipments);
return resolve(allShipments);
})
.catch(error => reject(error))
})
}
module.exports = {
createShipment,
getAllShipments
}
Shipment Router
var router = require('express').Router();
var Shipment = require('./../../../controllers/shipment');
router.post ('/' , (req,res) => {
Shipment.createShipment ('New Shipment', 'Pending')
.then (shipment => {
res.status(200).json({status: true, data: shipment, errors: null, msg: "Shipment Added Successfully"});
})
.catch (error => {
res.status(200).json({status: false, data: {}, errors: error, msg: "Error Creating Shipment. Please see details in Errors Object"});
});
});
router.get('/' , (req, res) => {
Shipment.getAllShipments()
.then(allShipments => {
return res.status(200).status({status: true, data: allShipments, errors: null, msg: "All Shipments fetched successfully"});
})
.catch(error => {
return res.status(200).json({status: false, data: {}, errors: error, msg: "Error Fetching Shipments. Please see details in Errors Object"});
});
})
module.exports = router;
What I'm doing wrong ? Because getAllShipments is giving my output on console but route is not sending response and just waiting and waiting.
Change :
Shipment.getAllShipments()
.then(allShipments => {
return res.status(200).status({status: true, data: allShipments, errors: null, msg: "All Shipments fetched successfully"});
})
to:
return res.status(200).json({status: true, data: allShipments, errors: null, msg: "All Shipments fetched successfully"});
Just a typo and you wrote down a status two times instead of json
I want to get data from form and based on that, add data to three tables in mySQL, I use Sequelize to do so, However I don't how to do so, my current idea gives error:
Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers
after they are sent to the client
My code is like this:
app.post("/device/add", (req, res) => {
db.Devices.create({
device_id: req.body.device_id,
server: req.body.server,
type: req.body.type
})
.then(result => {
res.json(result);
})
.catch(err => {
throw err;
});
db.Modules.create({
device_id: req.body.device_id,
device_options: req.body.device_options,,
sleep_options: req.body.sleep_options
})
.then(result => {
res.json(result);
})
.catch(err => {
throw err;
});
db.Tests.create({
device_id: req.body.device_id,
gsm_tests: req.body.gsm_tests,
led_tests: req.body.led_tests,
})
.then(result => {
res.json(result);
})
.catch(err => {
throw err;
});
});
can I somehow create it in one response? Or how to make it work
The problem is that you are trying to send again a response after you have sent one.
For more clarification, refer here
You can use Promise.all() to accumulate the results and then send it in one res.json() call.
const createDevice = db.Devices.create({
device_id: req.body.device_id,
server: req.body.server,
type: req.body.type
})
const createModules = db.Modules.create({
device_id: req.body.device_id,
device_options: req.body.device_options,
sleep_options: req.body.sleep_options
})
const createTests = db.Tests.create({
device_id: req.body.device_id,
gsm_tests: req.body.gsm_tests,
led_tests: req.body.led_tests,
})
Promise
.all([createDevice , createModules , createTests ])
.then(result=> {
res.json({
devices: result[0],
modules: result[1],
test : result[2]
});
})
.catch(err => {
throw(err);
});
I have programme in nodejs & mysql like below
db.query()
.then(1)
.then(2)
.then(3)
.catch()
I am checking a value from database in then(1) and trying to return response from there.In then(2) , I am executing another code that uses some data from result of then(1) and so on..
My problem: When returning response from then(1), catch() is calling(because then(2) have error, not getting data from then(1)) . So is there any way I can stop further execution in then(1) so that then(2) and catch() couldn't call ?
db.query('query......', [val1, val2])
.then(rslt => { return res.json({ mssg: "Email already exists!", error: "Email already exists!" }) })
.then(user => { return db.query('INSERT INTO ', value, (err, res, flds) => { err ? reject(err) : resolve(res) }) })
.then(user => { return res.json({ mssg: "Success", success: true}) })
.catch( (err) => { console.log(err) })
You can (and should) use an async function, instead of using the lower-level .then() API of the Promise object:
async function doTheThing() {
try {
const result = await db.query('...');
if (result) { // user exists
return res.json({...}); // this will end the entire function
}
const user = await db.query('...');
return res.json({...}); // success
} catch (err) {
console.log(err); // I don't recommend doing this. try/catch should be for recovery
}
}