Skip to content

Instantly share code, notes, and snippets.

@craigspaeth
Created March 10, 2014 23:48
Show Gist options
  • Save craigspaeth/9476858 to your computer and use it in GitHub Desktop.
Save craigspaeth/9476858 to your computer and use it in GitHub Desktop.
#
# A library of common cache helpers. If you need to do something more complex than
# the naive query caching Backbone Cache Sync (https://github.com/artsy/backbone-cache-sync)
# provides then it's recommended to wrap it up in a function in this lib.
#
_ = require 'underscore'
{ NODE_ENV, DEFAULT_CACHE_TIME, REDIS_URL } = require '../config'
redis = require 'redis'
client = null
# Setup redis client
if NODE_ENV is "development"
client = redis.createClient()
else if NODE_ENV isnt "test"
red = require("url").parse(REDIS_URL or "")
client = redis.createClient(red.port, red.hostname)
client.auth red.auth.split(":")[1]
# Caches a fetch until end call to reduce the many Redis GETs that could be potentially made.
#
# @param {Collection} collection The Backbone collection that calls fetchUntilEnd
# @params {Object} options Backbone options that would be passed into fetchUntilEnd
@cacheFetchUntilEnd = (collection, options = {}) ->
key = "fetch-until-end:" + _.result(collection, 'url') + JSON.stringify(options.data ? {})
success = options.success
client.get key, (err, json) ->
if err
options.error? err
else if json
obj = JSON.parse(json)
collection.set obj
success collection, obj
else
collection.fetchUntilEnd _.extend options,
success: ->
success arguments...
client.set key, JSON.stringify collection.toJSON()
client.expire key, DEFAULT_CACHE_TIME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment