I'm using `graphql-yoga`. Looking for insight on h...
# prisma-whats-new
w
I'm using
graphql-yoga
. Looking for insight on how to programmatically control if a field gets returned or not:
Copy code
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?
a
You could extend your
Event
resolver:
Copy code
const Event = {
  adminOnlySecret: async (parent, args, context, info) => {
    // Check if admin or not.
  }
};
I assume that you have the currently authenticated user in
context
. So your check would look something like:
Copy code
if (context.user.role !== “Admin”) {
    throw new Error(“Insufficient permissions.“)
}
An alternative approach would be to use: https://github.com/maticzav/graphql-shield
w
Where do I put the
ctx.db.query.event({}, info)
code if I extend my
Event
resolver?
a
No, you have to define it as an application resolver. Do you use Prisma?
w
I'm using prisma inside of graphql-yoga
a
Okay, cool. Do you have an
Event
resolver within your application?
w
Yes
a
Perfect. Then the approach above will work.
w
Copy code
async function event(parent, args, ctx, info) {
    const isAdmin = await checkAdmin(ctx)
    return ctx.db.query.event({}, info)
}
if I have something like that right now
and if they are admin, cool they can do whatever
but if they are not, then I need to hide that field
I'm still unclear how to change that resolver to do so
a
Very close 🙂 Look at this example:
Copy code
const Event = {
  adminOnlySecret: async (parent, args, context, info) => {
    // Check if admin or not.
  }
};

const resolvers = {
    Query, // Your query resolvers
    Mutation, // Your mutation resolvers
    Event
}
You create a “sub-resolver” on the
Event
and pass
Event
as an own resolver to your resolver map.
The function
adminOnlySecret
will be executed whenever somebody queries that field.
In general: You have a GraphQL schema and you map your resolvers functions to it.
w
I see... so then in
Copy code
const 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?
a
Exactly. 👍
w
and until now, I've been putting all of my query resolvers in the Query data structure. I still need to put
Copy code
function event(parent, args, ctx, info) {
    return ctx.db.query.event({}, info)
}
in there right?
a
No, this function is not necessary.
Ah, wait.
This is one resolver in the
Query
object?
w
yes, it returns an Event type
a
Ya, this is one resolver then for returning a particular event. Correct.
The actual sub-resolver has to be in the
Event
resolver though.
w
great, thanks a lot for your help!
a
You’re very welcome 🙂