3.3K Followers
·
Follow

GraphQL Context & Services

Having used GraphQL for quite some time, two of my favorite patterns are:

  • Context as a class
  • Abstracting complexity into Service APIs via context.services

Note: You can find the source code for the this screenshot & demo at:
https://github.com/ericclemmons/graphql-context-services/

Rationale

  • Using Context (instead of a plain {…} object) moves complexity from within your GraphQL middleware to a separate, testable layer.
Image for post
Image for post
  • Context can have a strict, testable API for your resolvers to use, instead of ad-hoc reliance on req.query or req.body .
Image for post
Image for post
This initialization pattern is compatible with Apollo’s Data Sources. Also, computed properties are readily testable without an E2E test.
  • API calls within resolvers are simplified, as their only responsibility is to shepherd arguments from the query to the service layer.
  • You can leverage Apollo’s dataSources, even with the standard express-graphql library!
Image for post
Image for post
RESTDataSource automatically caches based on HTTP response headers!

That’s it!

If you haven’t already, view & play with this example on CodeSandbox.

If you enjoyed this, give me a follow at @ericclemmons on Twitter!

Written by

I write about tech (JavaScript, node, GraphQL, React, webpack) and Leadership. Currently building GraphQL apps @Starbucks.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store