[英]How do you filter your JSON data before it is send to your front end based on role in Express and MongoDB?
I was searching online, but couldn't find any framework nor code that could help me.我在网上搜索,但找不到任何可以帮助我的框架或代码。
So what I want to do is that whenever I send a response to my front-end, I want to filter my data based on the users his role.所以我想做的是,每当我向前端发送响应时,我想根据用户的角色过滤我的数据。
For example:例如:
DB: D B:
User: (name, it_skill, current_project, finished_projects [])
If I send a GET request and my role = admin, I want to get all the information about the user, but If my role = employee, I don't want to recieve finished_projects[].如果我发送一个 GET 请求并且我的角色 = 管理员,我想获取有关用户的所有信息,但如果我的角色 = 员工,我不想收到 finished_projects[]。
I'm also searching for a DRY approach, at this moment I have the next code我也在寻找一种 DRY 方法,此时我有下一个代码
router.get('/user/:id', signedInCheck, hasRole('admin'), userController.getUserAsAdmin);
router.get('/user/:id', signedInCheck, hasRole('employee') userController.getUserAsEmployee);
And the only thing that different between getUserAsAdmin and getUserAsEmployee is the mongdo db code: getUserAsAdmin 和 getUserAsEmployee 之间唯一不同的是 mongdo db 代码:
UserDB.findById(user_id)
vs对比
UserDB.findById(user_id, '-finished_projects')
But is would be much smoother if just before my response my JSON string that I send gets checked.但是,如果在我的回复之前检查我发送的 JSON 字符串会更顺利。 because if I don't want to write 2 different kind of routes anytime I need another.
因为如果我不想在任何时候写两条不同的路线,我需要另一条路线。
Is there some kind of a framework for?是否有某种框架? Or a design pattern to implement this kind of thing
或者实现这种事情的设计模式
UserController: there are functions for retrieving data for user, like: UserController:有为用户检索数据的功能,例如:
// ADMIN FUNCTION
function getUserAsAdmin(){
// querying form db or retrieving data from model
// UserDB.findById(user_id)
// return your response;
}
// EMPLOYEE FUNCTION
function getUserAsEmployee(){
// querying form db or retrieving data from model
// UserDB.findById(user_id, '-finished_projects')
// return your response;
}
Just create a new function in this controller like below:只需在此 controller 中创建一个新的 function ,如下所示:
// ADMIN OR EMPLOYEE FUNCTION
function getUser(){
if ( hasRole('admin') ) {
// call admin function
getUserAsAdmin();
}
else if ( hasRole('employee') ) {
// call employee function
getUserAsEmployee();
}
}
And your single route will be like:你的单一路线将是这样的:
router.get('/user/:id', signedInCheck, userController.getUser);
If you have more then 2 roles or you want to check both roles in middleware in single function then you have to modify hasRole()
role checker function to check both from array, ex: role must be one from array如果您有超过 2 个角色,或者您想在单个 function 中检查中间件中的两个角色,那么您必须修改
hasRole()
角色检查器 function 以从数组中检查两者,例如:角色必须是数组中的一个
router.get('/user/:id', signedInCheck, hasRole(['admin', 'employee']) userController.getUser);
Hope this will help.希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.