Context
I have a GraphQL API and a NodeJS & Angular application with a MongoDB database that holds users. For each user, there is a public page with public information like id
and username
. When a user is logged in, there is a private profile page with extended information like an email
.
Just for context, I'm using jsonwebtoken with accesscontrol to authenticate and authorize a user. The information is stored on the Context of every GraphQL resolve function, so whatever is needed to identify a logged in user is available.
I have a GraphQL query that retrieves a public user like so:
query getUserById($id: ID!) {
getUserById(id: $id) {
id,
username
}
}
I am trying to think of the proper implementation to retrieve either a public or a private user. Since GraphQL is strong typed, I'm having some trouble coming up with a proper solution.
Question
How do I implement the distinction between a public and a private user?
Considerations
1. Separate query
So one of the options is to have a seperate query for both public and private fields:
public query
query getUserById($id: ID!) {
getUserById(id: $id) {
id,
username
}
}
private query
query getMe {
getMe {
id,
username,
email
}
}
2. Using GraphQL Interfaces
I came across this Medium article that explains how GraphQL Interfaces are used to return different Types based on a resolveType
function. So I would go something like so:
query getUser($id: ID!) {
getUser(id: $id) {
... on UserPrivate {
id,
username
}
... on UserPublic {
id,
username,
email
}
}
}
I have not came across a proper solution and I'm unsure about either of the consideration I have so far.
Any help is much appreciated!