Grapher + subscription cache

Hi there,

has anyone used Grapher + some kind of (client side) subscription cache (e.g. subs-cache)? Since the named queries have their own namedQuery.subscribe() method, I’m not sure what’s the easiest way to use this.

For future reference, I came up with this solution. It would be simpler to modify grapher (to allow an optional subscribe function instead of Meteor.subscribe, but this was faster. This will use the passed subsManager instance for every Named Query of this Collection. When user visits pageA (with a subscription), then navigates to pageB and finally back to pageA, the subscribed data will still be in their local minimongo and doesn’t have to go through the network again.

import { Meteor } from 'meteor/meteor'
import { SubsManager } from 'meteor/meteorhacks:subs-manager'

/**
 * changes the subscribe() method on the client
 * for named queries to use a subsManager
 * @param {Collection} Collection the collection instance
 * @param {SubsManager} [subsManager] optional subsManager instance
 */
export default function(Collection, subsManager) {
  if (!subsManager) subsManager = new SubsManager()
  const original = Collection.createQuery
  Collection.createQuery = function(...args) {
    const query = original.call(this, ...args)
    if (query.isNamedQuery) {
      query.subscribe = function(callback) {
        if (this.isResolver) {
          throw new Meteor.Error(
            'not-allowed',
            'You cannot subscribe to a resolver query'
          )
        }
        // this line is the only change: subsManager instead of Meteor
        this.subscriptionHandle = subsManager.subscribe(
          this.name,
          this.params,
          callback
        )
        return this.subscriptionHandle
      }
    }
    return query
  }
}

Then when you create a collection, you can call it like this:

// Items is a Mongo.Collection
if (Meteor.isClient) {
  const itemSubsManager = new SubsManager({ cacheLimit: 10, expireIn: 30 })
  useSubsManager(Items, itemSubsManager)
}

this package can help you
https://atmospherejs.com/lamhieu/hypersubs

1 Like