Note: These docs are for using Meteor with the 1.0 version of Apollo Client. The 2.0 upgrade is still in progress and these docs will be updated when it is ready
The Apollo client and server tools are published on npm, which makes them available to all JavaScript applications, including those written with Meteor 1.3 and above. When using Meteor with Apollo, you can use those npm packages directly, or you can use the apollo
Atmosphere package, which simplifies things for you.
To install apollo
, run these commands:
|
|
Usage
Examples
You can see this package in action in the Apollo Meteor starter kit.
If you’d like to understand how this simple package works internally, you are invited to take the code tour.
Client
Connect to the Apollo server with meteorClientConfig
:
|
|
Server
Create the following files:
|
|
Define a simple schema under schema.js
.
|
|
Define your first resolver under resolvers.js
.
|
|
Set up the Apollo server with createApolloServer
:
|
|
The GraphiQL url by default is http://localhost:3000/graphiql. You can now test your first query:
|
|
Inside your resolvers, if the user is logged in, their id will be context.userId
and their user doc will be context.user
:
|
|
Query batching
meteor/apollo
gives you a BatchedNetworkInterface
by default thanks to createMeteorNetworkInterface
. This interface is meant to reduce significantly the number of requests sent to the server.
In order to get the most out of it, you can attach a dataloader
to every request to batch loading your queries (and cache them!).
Here are some great resources to help you integrating query batching in your Meteor application:
- About batched network interface:
- Apollo Client documentation, the official documentation explaining how it works and how to set it up.
- Query batching in Apollo, an article from the Apollo blog with more in depth explanation.
- About Dataloader:
- Apollo’s Graphql server documentation, get to know how to setup
dataloader
in your server-side implementation. - Dataloader repository, a detailed explanation of batching & caching processes, plus a bonus of a 30-minute source code walkthrough video.
- Apollo’s Graphql server documentation, get to know how to setup
Deployment
It is strongly recommended to explictly specify the ROOT_URL
environment variable of your deployment. The configuration of the Apollo client and GraphQL server provided by this package depends on a configured ROOT_URL
. Read more about that in the Meteor Guide.
Typings
Your Meteor apps may rely on static typings with TypeScript. If so, it is recommended to use the ambient TypeScript definition for this Atmosphere package.
API
meteorClientConfig
meteorClientConfig(customClientConfig = {})
The customClientConfig
is an optional object that can have any Apollo Client options.
Defining a customClientConfig
object extends or replaces fields of the default configuration provided by the package.
The default configuration of the client is:
networkInterface
:createMeteorNetworkInterface()
, a pre-configured network interface. See below for more information.ssrMode
:Meteor.isServer
, enable server-side rendering mode by default if used server-side.
The store is normalized by default with __typename
+ _id
identifiers. See store normalization section for more information.
createMeteorNetworkInterface
createMeteorNetworkInterface(customNetworkInterface = {})
customNetworkInterface
is an optional object that replaces fields of the default configuration:
uri
:Meteor.absoluteUrl('graphql')
, points to the default GraphQL server endpoint, such as http://locahost:3000/graphql or https://www.my-app.com/graphql.opts
:{}
, additionalFetchOptions
passed to theNetworkInterface
.useMeteorAccounts
:true
, enable the Meteor User Accounts middleware to identify the user with every request thanks to her login token.batchingInterface
:true
, use aBatchedNetworkInterface
by default instead ofNetworkInterface
.batchInterval
:10
, if thebatchingInterface
field istrue
, this field defines the batch interval to determine how long the network interface batches up queries before sending them to the server.
Additionally, if the useMeteorAccounts
is set to true
, you can add to your customNetworkInterface
a loginToken
field while doing server-side rendering to handle the current user.
createMeteorNetworkInterface
example:
|
|
createApolloServer
createApolloServer(customOptions = {}, customConfig = {})
createApolloServer
is used to create and configure an Express GraphQL server.
customOptions
is an object that can have any GraphQL Server options
, used to enhance the GraphQL server run thanks to graphqlExpress
. Defining a customOptions
object extends or replaces fields of the default configuration provided by the package:
context
:{}
is an object or a function returning an object that extends the context object being passed down to the resolvers.formatError
: a function used to format errors before returning them to clients.debug
:Meteor.isDevelopment
, additional debug logging if execution errors occur in dev mode.
This is the object that should have a schema
entry created by makeExecutableSchema
.
customConfig
is an optional object that can be used to replace the configuration of how the Express server itself runs:
path
: path of the GraphQL server. This is the endpoint where the queries & mutations are sent. Default:/graphql
.configServer
: a function that is given to the express server for further configuration. You can for instance enable CORS withcreateApolloServer({}, {configServer: expressServer => expressServer.use(cors())})
graphiql
: whether to enable GraphiQL. Default:true
in development andfalse
in production.graphiqlPath
: path for GraphiQL. Default:/graphiql
(note the i).graphiqlOptions
: GraphiQL options Default: attempts to useMeteor.loginToken
from localStorage to log you in.
It will use the same port as your Meteor server. Don’t put a route or static asset at the same path as the GraphQL route or the GraphiQL route if in use (again, defaults are /graphql
and /graphiql
respectively).
Accounts
You may still use the authentication based on DDP (Meteor’s default data layer) and apollo
will send the current user’s login token to the GraphQL server with each request.
If you want to use only GraphQL in your app you can use nicolaslopezj:apollo-accounts. This package uses the Meteor Accounts methods in GraphQL, it’s compatible with the accounts you have saved in your database and you may use nicolaslopezj:apollo-accounts
and Meteor’s DDP accounts at the same time.
If you are relying on the current user in your queries, you’ll want to clear the store when the current user state changes. To do so, use client.resetStore()
in the Meteor.logout
callback:
|
|
SSR
There are two additional configurations that you need to keep in mind when using React Server Side Rendering with Meteor.
- Use
isomorphic-fetch
to polyfillfetch
server-side (used by Apollo Client’s network interface). - Connect your express server to Meteor’s existing server with WebApp.connectHandlers.use
- Do not end the connection with
res.send()
andres.end()
usereq.dynamicBody
andreq.dynamicHead
instead and callnext()
. more info
The idea is that you need to let Meteor to finally render the html you can just provide it extra body
and or head
for the html and Meteor will append it, otherwise CSS/JS and or other merged html content that Meteor serve by default (including your application main .js file) will be missing.
Here is a full working example:
|
|
Apollo Optics
Here’s a minimal example of Apollo Optics integration:
|
|
Importing .graphql
files
An easy way to work with GraphQL is by importing .graphql
files directly using the import
syntax.
|
|
Instead of the /imports/api/schema.js
file, create a /imports/api/schema.graphql
file with the same content as before:
|
|
One of the benefits you’ll get right away is good highlighting by GitHub and your IDE!
Now we can import the schema:
|
|
Use typeDefs
as before in the above examples. You can pass it directly to makeExecutableSchema
like before.
The import syntax will also work for any other .graphql
file besides your main schema. So you’ll be able to import query, mutation and subscription files without needing to manually parse them with the graphql-tag.
For more benefits, see the GrahpQL build plugin README.
Blaze
If you are looking to integrate Apollo with Blaze, you can use the swydo:blaze-apollo package:
|
|
This gives you reactive GraphQL queries in your templates!
|
|
Subscriptions
You can also use GraphQL subscriptions with your Meteor app if you need to. The following code gives an example of a complete configuration that enables all the features of subscriptions in addition to base GraphQL.
Client
|
|
Server
The same context
is used for both the resolvers and the GraphQL subscriptions. This also means that authentication in the websocket transport is configured out-of-the-box.
Note that PubSub
from graphql-subscriptions
is not suitable for production. You should wire your SubscriptionManager
with Redis subscriptions or MQTT subscriptions in case you want to use them in production apps.
|
|