Open riggedCoinflip opened 3 years ago
I think that you can achieve this with a resolver wrapper. You can wrap your findOne resolver to run code that limits the visible fields based on the user's role, something like this:
UserTC.mongooseResolvers.findOne.wrapResolve((next) => (rp) => {
const { role } = resolveParams.context;
rp.beforeQuery = (query: Query<unknown, never>) => {
if (role === 'admin') {
// Don't change the projection and allow all fields
} else if (role === 'moderator') {
query.select({ email: 0, password: 0 });
} else if (role === 'public') {
query.projection({ name: 1, favouriteColor: 1 });
}
};
return next(rp);
}),
You'll have to pass your role in as context. If you're using ApolloServer, there's a context
method you can use to add context to each request, and I'm sure that other GraphQL servers have a similar way of doing it. Hope that points you in the right direction!
I have a user model like this:
and I want to have different "views" for different permission roles: An admin has full access. A moderator can view all fields except
password
andemail
A basic user can only see thename
andfavouriteColor
.The way I am currently doing it (which works) is to create a different TC for every permission role:
but I have the feeling this is a suboptimal solution. If I have a custom resolver that I want to reuse in different
UserTC
s I have to copy-paste the code.I think it could be a good solution to whitelist fields resolver-based in the options. An example of how this could look like:
What do you think?