Wednesday 23 May 2018

[Question] Right way of passing consistent data from DB to user without repeatedly quering

Database stores some data about the user which almost never change. Well sometimes they do if the user wants it.Data like his name, username and his company data.The first two are being shown to his navigation bar all the time, like "User_1 is logged in", his company data when he needs to create an invoice.My current way is to fetch user data through middleware using router.use so they are always available for rendering through all routes/views, for example:.router.use(function(req, res ,next) { // this block of code is called in every route req.getConnection(function(err,conn){ uid = req.user.id; if(err){ console.log(err); return next("Mysql error, check your query"); } var query = conn.query('SELECT * FROM user_profile WHERE uid = ? ', uid, function(err,rows){ if(err){ console.log(err); return next(err, uid, "Mysql error, check your query"); } userData = rows; return next(); }); }); }) .I understand that this is not an optimal way of achieving user profile data to every route/view since it make DB queries every time the user navigates through the application.What would be a better way of having them available without repeating the same query in each route yet have them re-fetched when user changes a portion of this data, like his name ?

Submitted May 23, 2018 at 01:03PM by King_Cadmos

No comments:

Post a Comment