Let\'s say I have a User type that contains the following fields:
type User {
name: String
username: String
someOtherField1: String
someOtherField2: Stri
By default, GraphQL types are maybe types, which means you can return null to any field.
Which means, inside the resolve
function of your creditCardNumber
field, you could check if the current user is the user being fetched, and if so, you return the number. Otherwise, you return null.
To access "contexted" data such as the current user, GraphQL let you pass an object context
when executing the graphql function:
graphql(schema, query, rootValue, context) // <-- the last parameter
And you will find this object in each field resolve
function signature:
...
resolve: (object, args, context) => {
// Third argument is your object
},
....
So what you can do, is pass the current logged user in the context:
graphql(schema, query, rootValue, { user: getCurrentLoggedUser() })
And in your User
type, inside the creditCardNumber
field resolve function:
creditCardNumber: {
...
resolve: (user, args, context) => {
if (user.id === context.user.id)
return user.creditCardNumber;
return null;
},
...
}
If you are using graphql-express
, the context is by default the request, and you can customize it.