UNPKG

shortshort

Version:
113 lines (99 loc) 3.07 kB
// Generated by CoffeeScript 1.3.1 (function() { var ShortShort, base62, httpRegex; base62 = require("base62"); httpRegex = /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/i; ShortShort = (function() { ShortShort.name = 'ShortShort'; function ShortShort(redis, opts) { this.redis = redis; if (opts == null) { opts = {}; } if (this.redis == null) { throw "A redis connection is needed by ShortShort"; } this.validation = true; if (opts.validation != null) { this.validation = opts.validation; } this.globalCounter = opts.globalCounter || "ss-global-counter"; this.keyPrefix = opts.keyPrefix || "ss-key-"; this.latestList = opts.latestList || "ss-latest-list"; this.latestLength = opts.latestLength - 1 || 9; } ShortShort.prototype.shorten = function(url, callback) { var _this = this; if (this.validation && !httpRegex.test(url)) { callback({ message: "not an url" }); return; } return this.redis.incr(this.globalCounter, function(err, globalCounter) { var result; if (err != null) { callback(err); return; } result = { key: base62.encode(globalCounter) }; return _this.redis.set(_this.keyPrefix + result.key, url, function() { _this.redis.lpush(_this.latestList, result.key, function() { return _this.redis.ltrim(_this.latestList, _this.latestLength, function() {}); }); return callback(null, result); }); }); }; ShortShort.prototype.resolve = function(key, callback) { return this.redis.get(this.keyPrefix + key, function(err, value) { if (err != null) { callback(err); return; } if (value != null) { return callback(null, value); } else { return callback({ message: "key not found" }, null); } }); }; ShortShort.prototype.update = function(key, newValue, callback) { var _this = this; if (this.validation && !httpRegex.test(newValue)) { callback({ message: "not an url" }); return; } return this.resolve(key, function(err, oldValue) { if (err != null) { callback(err); return; } return _this.redis.set(_this.keyPrefix + key, newValue, function(err) { if (err != null) { callback(err); return; } return callback(null); }); }); }; ShortShort.prototype.latest = function(callback) { return this.redis.lrange(this.latestList, 0, this.latestLength, function(err, list) { if (err != null) { return callback(err, null); } else { return callback(null, list); } }); }; return ShortShort; })(); module.exports = ShortShort; }).call(this);