Giter VIP home page Giter VIP logo

blaze-apollo's Introduction

BlazeApollo

Blaze integration for the Apollo Client. Load GraphQL data directly in your templates!

Build Status Greenkeeper badge Conventional Commits

Github Header

As you might have noticed, Blaze-Apollo isn't actively maintained/developed, because we're moving to React ourselves. Blaze is great, but has a lot of quirks. We have more trust in React for future development and projects. If we can fix things with reasonable investment, we will, but Blaze-Apollo will stay mostly "as is". Thanks.

Table of Contents

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. ddp-apollo also give you subscriptions out of the box! Installation instructions are in the README of those packages.

Client

import ApolloClient from 'apollo-client';
import { setup } from 'meteor/swydo:blaze-apollo';

// When using the meteor/apollo package:
import { meteorClientConfig } from 'meteor/apollo';
const client = new ApolloClient(meteorClientConfig());

// When using meteor/swydo:ddp-apollo:
import { DDPNetworkInterface } from 'meteor/swydo:ddp-apollo';
const client = new ApolloClient ({
  networkInterface: new DDPNetworkInterface()
});

setup({ client });

Something to query

For the examples below we'll use the following data:

{
  human(id: "1000") {
    name
    height(unit: FOOT)
  }
}

The result will look like this:

{
  "data": {
    "human": {
      "name": "Luke Skywalker",
      "height": 5.643
    }
  }
}

Directly copied from the awesome GraphQL examples.

GraphQL Queries

<template name="human">
  <h1>{{human.name}}</h1>
  <p>The height of this human is {{human.height}} foot.</p>
</template>
import './human.html';
import HUMAN_QUERY from './humanQuery.graphql';

Template.human.helpers({
  human() {
    return Template.instance().gqlQuery({ query: HUMAN_QUERY }).get().human;
  }
});

And done! GraphQL data in your templates!

Besides query, all other options for ApolloClient.watchQuery are available. Like pollInterval, forceFetch, noFetch and variables.

GraphQL Mutations

Template.human.onCreated(function () {
  this.gqlMutate({
    query: HUMAN_MUTATION_QUERY
  });
});

GraphQL Subscriptions

This packages works with any Apollo Client that has subscriptions available. No special setup required.

Template.human.onCreated(function () {
  this.gqlSubscribe({
    query: HUMAN_SUBSCRIPTION_QUERY
  });
});

GraphQL subscribtions initiated with gqlSubscribe will automatically be unsubscribed when the template is destroyed!

General 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 ReactiveObserver with a reactive get() method, just like any ReactiveVar:

Template.myTemplate.onCreated(function() {
  const result = this.gqlQuery({ query: QUERY });

  // This is reactive
  result.get();

  // So this will rerun automatically when data in the cache changes
  // This includes updates from mutations and (GraphQL) subscriptions
  this.autorun(function() {
    result.get();
  });

  // Stop listening to updates
  // Note: This is automatically done when the template is destroyed
  result.unsubscribe();

  // Acess the original observer directly via the result
  result.observer.setVariables({});

  // Detect if a result is loaded for the first time, reactively
  result.isReady();
});

Generic template helpers

<template name="myTemplate">
  {{#if queriesReady}}
    <p>Loaded {{human.name}}</p>
  {{else}}
    <p>Loading...</p>
  {{/if}}
</template>

Testing

This package uses practicalmeteor:mocha for testing:

meteor test-packages ./ --driver-package practicalmeteor:mocha

Sponsor

Want to work with Meteor and GraphQL? Join the team!

blaze-apollo's People

Contributors

cliffzz avatar dependabot-preview[bot] avatar diegonc avatar greenkeeper[bot] avatar jamiter avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

blaze-apollo's Issues

get() throws when query result is undefined

I've just tripped into the exception below, triggered when the query result is still undefined.

Exception in template helper: SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at jsonClone (http://localhost:3000/packages/swydo_blaze-apollo.js?hash=c91866076c16a91ad56ef1526f5b5bc5a90bc9cc:78:15)
    at Result.get (http://localhost:3000/packages/swydo_blaze-apollo.js?hash=c91866076c16a91ad56ef1526f5b5bc5a90bc9cc:112:14)

It's happening because I'm doing a this.gplQuery and a get() in the same onCreated callback. Strange though, I tried to overcome the problem using isReady() but that method returned true even when the result was still undefined.

Clear Cache

I am trying to run a new query on the client and for the life of me I can not get not bypass the cached results
This is the code that I am running and changing the variables that are being used seems to have no effect on the result that is returned

const { user } = Template.instance().gqlQuery({
      query: USER_LUNCHES,
      vaiables: { userEmail: Session.get("email")},
    }).get();

Any help would be greatly appreciated currently I am at the banging my head on a wall stage...

Add loading property

Right now, whenever I want to display a query result, I have to safe access the returned objects property.

Example:

const myQuery = gql`
    {
        currentUser {
            favorites {
                title
                artist
            }
        }
    }
`;

// Somewhere in a Template.x.helpers
    favourites() {
        const queryResult = Template.instance().gqlQuery({ query: myQuery }).get();
        const currentUser = queryResult.currentUser || {}; // This is the tiring part
        return currentUser.favorites; // No safe access needed, returns either [] or undefined
    },

This is a bit tiring and repetative. I've seen in several examples (e. g. http://dev.apollodata.com/react/auth.html#login-logout) that there is a loading property for react. What do you think? Would this be great for this package as well?

Error on client

I have an error in my client:

Exception in template helper: TypeError: Template.instance(...).gqlQuery is not a function

Below my code:

import './directors.html';
import gql from 'graphql-tag';

const MY_QUERY = gql`{
	getDirectors {
    label
    hostname
    ip
  }
}`

Template.directors.helpers({
  directors() {
    return Template.instance()
      .gqlQuery({
        query: MY_QUERY
      })
      .get();

  }
});

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

How to use gqlSubscribe

Hi,

I am trying to get a refetch of the data that has been changed by a mutation but I can't get the query to rerun.
If I call the gqlSubscribe with the same query and variables I see the logs from the query reaching the new data but the gqlQuery is not rerun.
I couldn't find it in the docs how could I use the gqlSubscribe in a situation like this

Template.patientInfo.created = function() {
  this.member = new ReactiveVar(false);
  Session.set("showLoadingPatientForm", false);

  tempInst = this;
  this.autorun(function() {
    console.log(Session.get("showLoadingPatientForm"));
    if (Session.get("showLoadingPatientForm")) console.log("reload");
    if (FlowRouter.getParam("id")) {
      let variables = { _id: FlowRouter.getParam("id") };

      console.log("subs",
        Template.instance()
          .gqlSubscribe({
            query: GET_PATIENT,
            variables: variables
          })); // here I can see the query logs reach the new data but the gqlQuery won't run again
      let currentPatient = Template.instance()
        .gqlQuery({
          query: GET_PATIENT,
          fetchPolicy: "no-cache",
          variables: variables
        })
        .get();
      if (currentPatient && currentPatient.patient) {
        tempInst.member.set(currentPatient.patient);
        Session.set("showLoadingPatientForm", false);
      }
    } else {
      tempInst.member.set({});
    }
  });
};

An in-range update of standard-version is breaking the build 🚨

The devDependency standard-version was updated from 7.0.1 to 7.1.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

standard-version is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 22 commits.

  • 5c80907 chore(release): 7.1.0
  • 00512d0 revert: "chore(deps): bump conventional-changelog to v3.1.17"
  • 8168e51 ci(travis): add node 12 to testing matrix
  • d1480bd chore(deps): bump conventional-changelog to v3.1.17
  • 0273809 docs: correct link in readme
  • ba80a0c feat: Adds support for header (--header) configuration based on the spec. (#364)
  • bc606f8 fix(deps): update dependency conventional-changelog-conventionalcommits to v4.2.3 (#496)
  • 0e74e26 chore(deps): update dependency eslint to v6.7.2 (#444)
  • 3bbab00 chore(deps): update dependency mocha to v6.2.2 (#458)
  • d97e446 chore(deps): update dependency eslint-plugin-node to v10 (#451)
  • 35b90c3 fix(deps): update dependency yargs to v15 (#484)
  • 564d948 feat: custom 'bumpFiles' and 'packageFiles' support (#372)
  • d557372 fix: use require.resolve for the default preset (#465)
  • f3e6944 test: add a case for loading a configuration (issueUrlFormat) from package.json. (#486)
  • 995e592 chore(deps): update dependency coveralls to v3.0.9 (#489)

There are 22 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Reactiveness outside of Templates

Hello,

how would you approach using Apollo outside Templates?
For now I'm using the apolloClient, instantiated with new ApolloClient(config) directly. The biggest disadvantage is, however, that you don't have reactiveness using Tracker out of the box.

My use-case is using a mutation inside a function in many places.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.