Wednesday 23 May 2018

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

Database stores some data about the user which almost never change. Well sometimes information might change if the user wants to edit his name for example.Data information is about each user's 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 profile data when he needs to create an invoice.My current way is to fetch user data through middleware using `router.use` so the extracted information is always available for rendering through all routes/views, for example: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 passing user profile data to every route/view since it makes new DB queries every time the user navigates through the application.What would be a better way of having this data available without repeating the same query in each route yet having them re-fetched once when user changes a portion of this data, like his fullname ?

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

No comments:

Post a Comment