2011-08-24 04:42:27 +08:00
|
|
|
/**
|
|
|
|
* User: simon
|
|
|
|
* Date: 23/08/2011
|
|
|
|
* Time: 21:10
|
|
|
|
* Desc: retrieves users database_name from the redis metadatabase based on subdomain/username
|
|
|
|
*/
|
|
|
|
|
2011-08-24 20:46:36 +08:00
|
|
|
var RedisPool = require("./redis_pool")
|
|
|
|
, _ = require('underscore')
|
|
|
|
, Step = require('step');
|
2011-08-24 04:42:27 +08:00
|
|
|
|
2011-08-24 20:46:36 +08:00
|
|
|
|
|
|
|
module.exports = function() {
|
2011-08-24 04:42:27 +08:00
|
|
|
var me = {
|
|
|
|
metadata_database: 5,
|
|
|
|
user_key: "rails:users:<%= username %>"
|
|
|
|
};
|
|
|
|
|
2011-08-24 20:46:36 +08:00
|
|
|
/**
|
|
|
|
* Get the database name for this particular subdomain/username
|
|
|
|
*
|
|
|
|
* @param req - standard express req object. importantly contains host information
|
|
|
|
* @param callback
|
|
|
|
*/
|
|
|
|
me.getDatabase = function(req, callback) {
|
|
|
|
// strip subdomain from header host
|
|
|
|
var username = req.headers.host.split('.')[0]
|
|
|
|
var redisKey = _.template(this.user_key, {username: username});
|
|
|
|
|
|
|
|
this.retrieve(redisKey, 'database_name', callback);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the user id for this particular subdomain/username
|
|
|
|
*
|
|
|
|
* @param req - standard express req object. importantly contains host information
|
|
|
|
* @param callback
|
|
|
|
*/
|
|
|
|
me.getId= function(req, callback) {
|
2011-08-24 04:42:27 +08:00
|
|
|
// strip subdomain from header host
|
|
|
|
var username = req.headers.host.split('.')[0]
|
2011-08-24 20:46:36 +08:00
|
|
|
var redisKey = _.template(this.user_key, {username: username});
|
|
|
|
|
|
|
|
this.retrieve(redisKey, 'id', callback);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Make a data access call to Redis
|
|
|
|
*
|
|
|
|
* @param redisKey - the base redis key where the metadata hash lives
|
|
|
|
* @param hashKey - the specific metadata you want to retrieve
|
|
|
|
* @param callback - function to pass metadata too. err,data args
|
|
|
|
*/
|
|
|
|
me.retrieve = function(redisKey, hashKey, callback) {
|
|
|
|
var that = this;
|
2011-08-24 04:42:27 +08:00
|
|
|
var redisClient;
|
|
|
|
|
|
|
|
Step(
|
2011-08-24 20:46:36 +08:00
|
|
|
function getRedisClient() {
|
|
|
|
RedisPool.acquire(that.metadata_database, this);
|
2011-08-24 04:42:27 +08:00
|
|
|
},
|
2013-03-14 18:58:30 +08:00
|
|
|
function lookupMetadata(err, data) {
|
|
|
|
if (err) throw err;
|
2011-08-24 04:42:27 +08:00
|
|
|
redisClient = data;
|
2011-08-24 20:46:36 +08:00
|
|
|
redisClient.HGET(redisKey, hashKey, this);
|
2011-08-24 04:42:27 +08:00
|
|
|
},
|
2011-08-24 20:46:36 +08:00
|
|
|
function releaseRedisClient(err, data) {
|
2013-03-14 18:58:30 +08:00
|
|
|
if ( redisClient ) RedisPool.release(that.metadata_database, redisClient);
|
2011-08-24 04:42:27 +08:00
|
|
|
callback(err, data);
|
|
|
|
}
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
return me;
|
2012-10-18 17:35:06 +08:00
|
|
|
}();
|