CartoDB-SQL-API/app/models/metadata.js

76 lines
2.2 KiB
JavaScript
Raw Normal View History

/**
* 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 20:46:36 +08:00
module.exports = function() {
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) {
// 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;
var redisClient;
Step(
2011-08-24 20:46:36 +08:00
function getRedisClient() {
RedisPool.acquire(that.metadata_database, this);
},
2013-03-14 18:58:30 +08:00
function lookupMetadata(err, data) {
if (err) throw err;
redisClient = data;
2011-08-24 20:46:36 +08:00
redisClient.HGET(redisKey, hashKey, this);
},
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);
callback(err, data);
}
);
};
return me;
2012-10-18 17:35:06 +08:00
}();