UNPKG

redis-node

Version:

A Complete Redis Client for Node.js

76 lines (64 loc) 2.36 kB
/* © 2010 by Brian Noguchi 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. */ var HashRing = require("./hashRing").HashRing, Url = require("url"); var Distributed = function Distributed (urls, options) { var urlObj; options = options || {}; this.tag = options.tag || /^\{(.+?)\}/; delete options.tag; this.default_options = options; this.ring = new HashRing(urls.map( function (url) { urlObj = Url.parse(url); redis.createClient(urlObj.port, urlObj.hostname, options); })); this.nodes = this.ring.nodes; }; Distributed.prototype = { nodeFor: function (key) { return this.ring.getNode(this.keyTag(key) || key); }, addNode: function (url) { var urlObj = Url.parse(url); this.ring.addNode( redis.createClient(urlObj.port, urlObj.hostname, this.default_options) ); }, /* Distributed Commands */ exists: function (key, callback) { this.nodeFor(key).exists(key, callback); }, /* Distributed Helpers */ onEachNode: function () { var args = Array.prototype.slice.call(arguments), commandName = args.shift(), nodes = this.nodes, i, len, node; for (i = 0, len = nodes.length; i < len; i++) { node = nodes[i]; node[command].apply(node, args); } }, keyTag: function (key) { var tag; if (tag = this.tag) { return key[this.tag, 1]; } } };