Permalink
Browse files

Merge pull request #6 from odbol/master

Added a few option features
  • Loading branch information...
2 parents a9273e4 + 0c0a032 commit 7026e7475f06dc4de0a7ae7a2dabb06e10c30dad @balor committed Jan 8, 2013
Showing with 34 additions and 2 deletions.
  1. +2 −0 Readme.md
  2. +32 −2 lib/connect-memcached.js
View
@@ -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).
@@ -50,16 +50,23 @@ module.exports = function(connect){
*/
function MemcachedStore(options) {
+ var log = options.loggingFunction || console.log;
+
options = options || {};
Store.call(this, options);
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);
+ log("MemcachedStore initialized for servers: " + options.hosts);
this.client.on("issue", function(issue) {
- console.log("MemcachedStore::Issue @ " + issue.server + ": " +
+ log("MemcachedStore::Issue @ " + issue.server + ": " +
issue.messages + ", " + issue.retries + " attempts left");
});
};
@@ -71,6 +78,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 +103,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 +127,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 +150,8 @@ module.exports = function(connect){
*/
MemcachedStore.prototype.destroy = function(sid, fn) {
+ sid = this.getKey(sid);
+
this.client.del(sid, fn);
};

0 comments on commit 7026e74

Please sign in to comment.