Skip to content
Browse files

First commit, add node-caching.

  • Loading branch information...
0 parents commit 624dc57aca797c6938df45fe2840ad594bcd068c @mape committed Aug 23, 2011
Showing with 202 additions and 0 deletions.
  1. +1 −0 .gitignore
  2. +22 −0 LICENSE
  3. +67 −0 README.md
  4. +76 −0 lib/caching.js
  5. +20 −0 npm-debug.log
  6. +16 −0 package.json
1 .gitignore
@@ -0,0 +1 @@
+node_modules
22 LICENSE
@@ -0,0 +1,22 @@
+(The MIT License)
+
+Copyright (c) 2011 Mathias Pettersson, mape@mape.me
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
67 README.md
@@ -0,0 +1,67 @@
+# node-caching
+
+Makes working with caching easier.
+
+## Installation
+
+Via [npm](http://github.com/isaacs/npm):
+
+ $ npm install caching
+
+## Pseudo code example
+ var Caching = require('caching');
+ var cache = new Caching('redis');
+
+ var ttl = 60 * 1000 // 1minute;
+ cache('twitter-users', ttl, function(passalong) {
+ getMostActiveTwitterUser(function(err, userName) {
+ fetchTwitterFollowers(userName, passalong); // passalong replaces function(err, userList) {}
+ })
+ }, function(err, userList) {
+ console.log(userList);
+ });
+
+## Code example
+ var Caching = require('caching');
+ var cache = new Caching('redis');
+
+ setInterval(function() {
+ cache('key', 10000 /*ttl in ms*/, function(passalong) {
+ // This will only run once, all following requests will use cached data.
+ setTimeout(function() {
+ passalong(null, 'Cached result');
+ }, 1000);
+ }, function(err, results) {
+ // This callback will be reused each call
+ console.log(results);
+ });
+ }, 100);
+
+
+## Built in stores
+* Memory
+* Redis
+
+## Api
+
+ cache(key, ttl, runIfNothingInCache, useReturnedCachedResults);
+
+### arguments[0]
+Key, `'myKey'`
+### arguments[1]
+Time To Live in ms, `60*30*1000`
+### arguments[2]
+Callback that will run if results aren't already in cache store.
+
+ function(passalong) {
+ setTimeout(function() {
+ passalong(null, 'mape', 'frontend developer', 'sweden');
+ }, 1000);
+ }
+
+### arguments[3]
+Callback that is called every time the method runs.
+
+ function(err, name, position, location) {
+ console.log(userList);
+ }
76 lib/caching.js
@@ -0,0 +1,76 @@
+var MemoryStore = function() {
+ var cache = {};
+ return {
+ 'get': function(key,callback) {
+ callback(null, cache[key] || null);
+ }
+ , 'set': function(key, ttl, result) {
+ cache[key] = result;
+ if (ttl) {
+ setTimeout(function() {
+ delete cache[key];
+ }, ttl);
+ }
+ }
+ };
+};
+var RedisStore = function() {
+ var redis = require('redis');
+ var redisClient = redis.createClient();
+ return {
+ 'get': function(key,callback) {
+ redisClient.get(key, function(err, result) {
+ callback(err, JSON.parse(result));
+ });
+ }
+ , 'set': function(key, ttl, result) {
+ if (ttl) {
+ redisClient.SETEX(key, Math.ceil(ttl/1000), JSON.stringify(result));
+ } else {
+ redisClient.set(key, JSON.stringify(result));
+ }
+ }
+ };
+};
+
+module.exports = Caching = function Caching(store) {
+ if (!store) {
+ store = new MemoryStore;
+ } else if (typeof store === 'string') {
+ switch(store.toLowerCase().trim()) {
+ case 'memory':
+ store = new MemoryStore;
+ break;
+ case 'redis':
+ store = new RedisStore;
+ break;
+ case 'memcache':
+ store = new MemcacheStore;
+ break;
+ default:
+ throw new Error('No built in store named "'+store+'".');
+ return;
+ }
+ }
+
+ var queues = {};
+ return function(key, ttl, workCallback, callback) {
+ store.get(key, function(err, storageData) {
+ if (!err && storageData) {
+ callback.apply(null, storageData);
+ } else if (queues[key]) {
+ queues[key].push(callback);
+ } else {
+ queues[key] = [callback];
+ workCallback(function() {
+ var args = Array.prototype.slice.call(arguments, 0);
+ store.set(key, ttl, args);
+ queues[key].forEach(function(queuedCallback) {
+ queuedCallback.apply(null, args);
+ });
+ delete queues[key];
+ });
+ }
+ });
+ };
+};
20 npm-debug.log
@@ -0,0 +1,20 @@
+info it worked if it ends with ok
+verbose cli [ 'node', '/usr/local/bin/npm', 'link', '-g' ]
+info using npm@1.0.8
+info using node@v0.4.9
+verbose config file /home/mape/.npmrc
+verbose config file /usr/local/etc/npmrc
+ERR! Error: link should never be --global.
+ERR! Please re-run this command with --local
+ERR! at Object.link (/usr/local/lib/node_modules/npm/lib/link.js:33:15)
+ERR! at /usr/local/lib/node_modules/npm/bin/npm.js:56:27
+ERR! at Array.0 (/usr/local/lib/node_modules/npm/npm.js:178:38)
+ERR! at EventEmitter._tickCallback (node.js:126:26)
+ERR! Report this *entire* log at:
+ERR! <http://github.com/isaacs/npm/issues>
+ERR! or email it to:
+ERR! <npm-@googlegroups.com>
+ERR!
+ERR! System Linux 2.6.26-2-amd64
+ERR! command "node" "/usr/local/bin/npm" "link" "-g"
+verbose exit [ 1, true ]
16 package.json
@@ -0,0 +1,16 @@
+{
+ "name" : "caching",
+ "description" : "Easier caching in node.js",
+ "version" : "0.0.1",
+ "author" : "Mathias Pettersson <mape@mape.me>",
+ "engines" : ["node"],
+ "directories" : { "lib" : "./lib" },
+ "main" : "./lib/caching",
+ "repositories" : [
+ { "type":"git", "url":"http://github.com/mape/node-caching" }
+ ],
+ "dependencies" : {
+ "hiredis" : ">=0.1.12",
+ "redis" : ">=0.6.7"
+ }
+}

0 comments on commit 624dc57

Please sign in to comment.
Something went wrong with that request. Please try again.