BlazeApollo
Blaze integration for the Apollo Client. Load GraphQL data directly in your templates!
Installation
meteor add swydo:blaze-apollo
meteor npm install --save apollo-client
Setup
Server
Before using this package it's recommended to first setup you GraphQL server. You can use the apollo package, which uses express and HTTP requests. Or use swydo:ddp-apollo, which leverages your current DDP connection, without setting up an HTTP server. Installation instructions are in the README of those packages.
Client
1import ApolloClient from 'apollo-client'; 2import { setup } from 'meteor/swydo:blaze-apollo'; 3 4// When using the meteor/apollo package: 5import { meteorClientConfig } from 'meteor/apollo'; 6const client = new ApolloClient(meteorClientConfig()); 7 8// When using meteor/swydo:ddp-apollo: 9import { DDPNetworkInterface } from 'meteor/swydo:ddp-apollo'; 10const client = new ApolloClient ({ 11 networkInterface: new DDPNetworkInterface({ connection: Meteor.connection }) 12}); 13 14setup({ client });
Something to query.
For the examples below we'll use the following data:
1import gql from 'graphql-tag'; 2 3const HUMAN_QUERY = gql` 4{ 5 human(id: "1000") { 6 name 7 height(unit: FOOT) 8 } 9} 10`;
The result will look like this:
1{ 2 "data": { 3 "human": { 4 "name": "Luke Skywalker", 5 "height": 5.6430448 6 } 7 } 8}
Directly copied from the awesome GraphQL examples.
Basic template example
<template name="human"> <h1></h1> <p>The height of this human is foot.</p> </template>
1import './human.html'; 2 3Template.human.helpers({ 4 human() { 5 return Template.instance().gqlQuery({ query: HUMAN_QUERY }).get().human; 6 } 7});
And done! GraphQL data in your templates!
Besides query, all other options for ApolloClient.watchQuery are available. Like pollInterval, forceFetch, noFetch and variables.
Deep dive into the API
The example above is great for a quick setup, but sometimes you need more control. We can do that by catching the result of the query. This gives us a Result variable with a reactive get() method, just like any ReactiveVar:
1Template.myTemplate.onCreated(function() { 2 const result = this.gqlQuery({ query: QUERY }); 3 4 // This is reactive 5 result.get(); 6 7 // So this will rerun automatically when data in the cache changes 8 // This includes updates from mutations and (GraphQL) subscriptions 9 this.autorun(function() { 10 result.get(); 11 }); 12 13 // Stop listening to updates 14 // Note: This is automatically done when the template is destroyed 15 result.unsubscribe(); 16 17 // You might need some control over the observer 18 // It's simply available on the result 19 result.observer.setVariables({}); 20});
Generic template helpers.
<template name="myTemplate"> <p>Loaded </p> <p>Loading...</p> </template>
Testing
This package uses practicalmeteor:mocha for testing:
meteor test-packages ./ --driver-package practicalmeteor:mocha