graphqlgraphql-javaspring-graphql

GraphQL hide certain fields from a response


I am completely new to GraphQL - apologies if this is a stupid question.

I have a Spring Boot application running GraphQL and have two endpoints as defined in my schema below:

type Query {
  userById(id: ID): User
  getMe: User
}

type User {
    id: ID!
    email: String!
    firstName: String!
    lastName: String!
}

getMe is an authorised endpoint and can only be accessed with a JWT authorization bearer. This returns the currently logged in user.

userById is open and allows a query to pull user information from an ID.

I would like to limit the type User for the userById query to remove the email field as (for this example) I don't want anyone to be able to query for someone's email address.

I could accomplish this by creating another User type (EG PublicUser) which doesn't contain the email field, however this seems incorrect to me. See an example of this implementation below:

type Query {
  userById(id: ID): PublicUser
  getMe: PrivateUser
}

interface User {
  id: ID!
  firstName: String!
  lastName: String!
}

type PrivateUser implements User {
  id: ID!
  email: String!
  firstName: String!
  lastName: String!
}

type PublicUser implements User {
  id: ID!
  firstName: String!
  lastName: String!
}

What is the standard way to accomplish this in GraphQL? I am using a Spring Boot GraphQL implementation, however an answer outlining the general practice used will set me in the right direction.

Thanks


Solution

  • Your approach is perfectly fine. Another approach would be to allow the email field to be nullable and just not return it when the requesting user is not the same as the user being requested.