Getting GraphQL to play nicely with Parse Server and React Native

graphqlparseparse serverreact native

This is a long overdue writeup on our experience setting up GraphQL and Parse Server together for the React Native TodoMVC project.

TL;DR

We’ve released two packages to make using authenticated GraphQL queries with Parse easier: Parse GraphQL Client and Parse GraphQL Server. You can see both of them in action in TodoMVC for React Native.

Setting it up

If you have been using Parse, you probably know that it uses object level security based on ACL (Access Control Lists). Enforcing these constraints in queries is done by passing user’s session token along. For example:

In order to make your GraphQL resolvers aware of these constraints, a few things need to happen.

Getting authorization information from the client

Regardless of what GraphQL client you are using, you will have to pass authorization information (session token in our case) along with your GraphQL query/mutation. Assuming you put Parse session token inside ‘Authorization’ header of the request, your server code will look as follows (using Express GraphQL):

Setting up resolvers

Once this is in place, resolvers in your schema will have access to a context variable (which in our case points to a session token):

Rinse and repeat

Any new resolver you will be writing, will have to systematically refer to the sessionToken and pass it along to various methods in Parse.Query and Parse.Object (and child classes). Needless to say, this is error prone and somewhat excessive.

Suggested solution

Parse GraphQL Client and Parse GraphQL Server take care of passing session tokens all the way from your client to the server and configuring Parse to use them in all the queries and updates/deletes.

Client side

Here is how you issue a GraphQL query with Parse session information attached to it in your React Native app:

Server side

First of all, you will need to register Parse GraphQL server with your Express app instance.

And now your resolvers will look as follows:

Notice how resolver context already contains current user and a configured Query class based on Parse.Query. For a complete example of Todo resolver refer to TodoMVC for React Native.

Done!

All your queries and mutations arrive to the server with corresponding session information attached to them and all your resolvers automatically propagate it to Parse using Query class from the context.

Credits

Parse GraphQL client is based on Lokka GraphQL client from folks at Kadira. Parse GraphQL server sits on top Lee Byron’s Express GraphQL.

Subscribe to our mailing list

Every week or so we send out a little email sharing something interesting about JavaScript, React, React Native, Meteor and cakes. We'd love to have you onboard. Also, no spam (pinky swear)