Meteor.user() Knows What Client Is Calling the Server?

My Meteor app uses swydo/ddp-apollo to access Apollo. I’m coding an Apollo GraphQL field resolver, and it needs to know what logged-in user is calling the Apollo endpoint.

Normally in the resolver, I can check const userid = context.userId for this. But in this case, the field resolver is defined separately in the schema from the query resolver, and so far I haven’t found the correct way to communicate context to the field resolver.

So on a whim I tried putting in const userData = Meteor.user(). It seems to return the data for the same user who would be identified via const userid = context.userId.

This is great - but - I’d like to understand what’s happening. How can the Meteor server tell what logged-in user is calling the Apollo back-end?

ddp-apollo does a few things

For requests over DDP, they use Meteor.methods here, which means they get all the same user context that you normally would in a plain method.
This is how they populate the context object here

As for the question about Meteor.user(), this method looks if it is currently in a method execution (or publication) and fetches the data from there.
Because JS is single threaded, it’s roughly as simple as this:

< -- new request received
currentConnection = request.connection
executeMethod()
 -- > request returned
currentConnection = null

and Meteor.user() does something like currentConnection.user

The reality is more complicated because of Fibers (ie executions are bound to a fiber with the connection information attatched to that fiber), but this mental model should help you understand

Related: for HTTP, they add their own authentication middleware here, which reads the login token from the request and fetches the current user, so they can create a context here and they create a method invocation wrapper so functions like Meteor.user() work there too.

1 Like

That is very cool. Another win for using Meteor in general and Meteor + swydo/ddp-apollo in this case as well. Thanks very much for this info.