GraphQL Helpers
A set of utilities for making it easier to work with graphql-js
.
- Allows creation of types and interfaces via the GraphQL schema syntax
- Generic resolvers and resolver decorators for common use cases.
Installation
npm install --save graphql-helpers
Basic usage
;; const registry = ; registry
If you have any types defined using the underlying graphql-js
library you can add them to the registry using registry.addType(type: GraphQLObjectType)
and registry.addInterface(interface: GraphQLIntefaceType)
. You can use types from the registry with registry.getType(name: String)
, which will allow you to incrementally adopt this pattern. To use a type from the registry in a vanilla graphql-js
type you should use a thunk for the fields to avoid any issues with types that haven't yet been registered.
Splitting your schema into modules.
If you want to split your types up into modules (as you probably should), to avoid having to manually import each one, you can cheat. There's a babel plugin called babel-plugin-import-glob
which lets you define a glob pattern of modules to bulk import.
Example
// Category.graphql.js { registry
// Product.graphql.js { registry
// Query.graphql.js { registry}
// schema.js ;; /* babel-plugin-import-glob turns this into the full list of modules, works with webpack */; const registry = ; /* Initialize modules */Object; const schema = query: registry;
Generic resolvers and resolver decorators
Certain types of resolver functions often get reused heavily, particularly field aliasing, so they're available to use in a generic form:
;;;; ; const registry = ; registry
Working with Relay
graphql-helpers
was born out of the requirements of existing Relay-based codebases, so it's important that building for Relay's specific schema requirements is as straightforward as possible. We achieve this by using a system of middleware. Middleware allows a Registry
to run post-processing steps on the schema types that its given, in the case of the Relay middleware, it does 2 things:
-
Automatically creates a resolve function for
ID
field types that generates a suitable Global ID for use with Relay nodes. -
Automatically converts mutation field arguments into a Relay-compatible Input type, and adds a
clientMutationId
field to both the input and output payload.
Example of Relay-compatible schema definition
; ;; const registry = middleware; registry; registry; registry; registry; registry; query: registry mutation: registry;
We also provide helper functions to make it easy to retrieve the underlying ID values when global IDs are used in a mutation input:
; ; registry; const eventArgs = ` id: ID! name: String! startDatetime: Datetime! endDatetime: Datetime! description: String venueId: String! tagIds: [String] `; registry;