Skip to content
Browse files

added support for memcache key prefixes

  • Loading branch information...
1 parent a9273e4 commit b41e3fdc1b0ece8d45054f805e30c7c4387ebc36 @odbol committed Oct 25, 2012
Showing with 30 additions and 0 deletions.
  1. +2 −0 Readme.md
  2. +28 −0 lib/connect-memcached.js
View
2 Readme.md
@@ -56,6 +56,8 @@
## Options
- `hosts` Memcached servers locations, can by string, array, hash.
+ - `prefix` An optional prefix for each memcache key, in case you are sharing
+ your memcached servers with something generating its own keys.
- ... Rest of given option will be passed directly to the node-memcached constructor.
For details see [node-memcached](http://github.com/3rd-Eden/node-memcached).
View
28 lib/connect-memcached.js
@@ -55,6 +55,11 @@ module.exports = function(connect){
if (!options.hosts) {
options.hosts = '127.0.0.1:11211';
}
+
+ if (options.prefix) {
+ this.prefix = options.prefix;
+ }
+
this.client = new Memcached(options.hosts, options);
console.log("MemcachedStore initialized for servers: " + options.hosts);
@@ -71,6 +76,23 @@ module.exports = function(connect){
MemcachedStore.prototype.__proto__ = Store.prototype;
/**
+ * A string prefixed to every memcached key, in case you want to share servers
+ * with something generating its own keys.
+ * @api private
+ */
+ MemcachedStore.prototype.prefix = '';
+
+ /**
+ * Translates the given `sid` into a memcached key, optionally with prefix.
+ *
+ * @param {String} sid
+ * @api private
+ */
+ MemcachedStore.prototype.getKey = function getKey(sid) {
+ return this.prefix + sid;
+ };
+
+ /**
* Attempt to fetch session by the given `sid`.
*
* @param {String} sid
@@ -79,6 +101,8 @@ module.exports = function(connect){
*/
MemcachedStore.prototype.get = function(sid, fn) {
+ sid = this.getKey(sid);
+
this.client.get(sid, function(err, data) {
try {
if (!data) {
@@ -101,6 +125,8 @@ module.exports = function(connect){
*/
MemcachedStore.prototype.set = function(sid, sess, fn) {
+ sid = this.getKey(sid);
+
try {
var maxAge = sess.cookie.maxAge
var ttl = 'number' == typeof maxAge ? maxAge / 1000 | 0 : oneDay
@@ -122,6 +148,8 @@ module.exports = function(connect){
*/
MemcachedStore.prototype.destroy = function(sid, fn) {
+ sid = this.getKey(sid);
+
this.client.del(sid, fn);
};

0 comments on commit b41e3fd

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