wallslide
02/14/2018, 11:02 AMgraphql-yoga
. Looking for insight on how to programmatically control if a field gets returned or not:
type Event {
id: ID!
adminOnlySecret: String
}
How do I write a resolver that returns/hides adminOnlySecret
using graphql-yoga
, depending on something like whether the person requesting the Event
is an admin or not?andre
02/14/2018, 11:04 AMEvent
resolver:
const Event = {
adminOnlySecret: async (parent, args, context, info) => {
// Check if admin or not.
}
};
andre
02/14/2018, 11:05 AMcontext
. So your check would look something like:
if (context.user.role !== “Admin”) {
throw new Error(“Insufficient permissions.“)
}
andre
02/14/2018, 11:05 AMwallslide
02/14/2018, 11:06 AMctx.db.query.event({}, info)
code if I extend my Event
resolver?andre
02/14/2018, 11:06 AMwallslide
02/14/2018, 11:07 AMandre
02/14/2018, 11:08 AMEvent
resolver within your application?wallslide
02/14/2018, 11:08 AMandre
02/14/2018, 11:08 AMwallslide
02/14/2018, 11:09 AMasync function event(parent, args, ctx, info) {
const isAdmin = await checkAdmin(ctx)
return ctx.db.query.event({}, info)
}
wallslide
02/14/2018, 11:09 AMwallslide
02/14/2018, 11:09 AMwallslide
02/14/2018, 11:09 AMwallslide
02/14/2018, 11:09 AMandre
02/14/2018, 11:10 AMandre
02/14/2018, 11:11 AMconst Event = {
adminOnlySecret: async (parent, args, context, info) => {
// Check if admin or not.
}
};
const resolvers = {
Query, // Your query resolvers
Mutation, // Your mutation resolvers
Event
}
andre
02/14/2018, 11:12 AMEvent
and pass Event
as an own resolver to your resolver map.andre
02/14/2018, 11:12 AMadminOnlySecret
will be executed whenever somebody queries that field.andre
02/14/2018, 11:13 AMwallslide
02/14/2018, 11:15 AMconst Event = {
adminOnlySecret: async (parent, args, context, info) => {
// Check if admin or not.
}
};
I use prisma to query using ctx.db.event({where: {id: 'someId'}}, '{adminOnlySecret}')
, and then either return that, or ""
depending on if they are an admin or not?andre
02/14/2018, 11:15 AMwallslide
02/14/2018, 11:17 AMfunction event(parent, args, ctx, info) {
return ctx.db.query.event({}, info)
}
in there right?andre
02/14/2018, 11:18 AMandre
02/14/2018, 11:18 AMandre
02/14/2018, 11:18 AMQuery
object?wallslide
02/14/2018, 11:19 AMandre
02/14/2018, 11:19 AMandre
02/14/2018, 11:20 AMEvent
resolver though.wallslide
02/14/2018, 11:20 AMandre
02/14/2018, 11:20 AM