Skip to content

Commit

Permalink
refactoring and cleaning up directories
Browse files Browse the repository at this point in the history
  • Loading branch information
evantahler committed Dec 24, 2011
1 parent eec3f29 commit f8c7385
Show file tree
Hide file tree
Showing 21 changed files with 702 additions and 615 deletions.
File renamed without changes.
631 changes: 50 additions & 581 deletions api.js

Large diffs are not rendered by default.

22 changes: 0 additions & 22 deletions cron.js

This file was deleted.

81 changes: 81 additions & 0 deletions initializers/initActions.js
@@ -0,0 +1,81 @@
////////////////////////////////////////////////////////////////////////////
// populate actions

var initActions = function(api, next)
{
api.actions = {};

var actionsPath = process.cwd() + "/actions/";
api.path.exists(actionsPath, function (exists) {
if(!exists){
var defaultActionsPath = __dirname + "/actions/";
api.log("no ./actions path in project, loading defaults from "+defaultActionsPath, "yellow");
actionsPath = defaultActionsPath;
}
api.fs.readdirSync(actionsPath).forEach( function(file) {
if (file != ".DS_Store"){
var actionName = file.split(".")[0];
var thisAction = require(actionsPath + file)["action"];
api.actions[thisAction.name] = require(actionsPath + file).action;
api.log("action loaded: " + actionName, "blue");
}
});
next();
});

api.logAction = function(api, connection){
if(api.models != null && api.models.log != null){
var logRecord = api.models.log.build({
ip: connection.remoteIP,
action: connection.action,
error: connection.error,
params: JSON.stringify(connection.params)
});
process.nextTick(function() { logRecord.save(); });
}
}

api.processAction = function(api, connection, next){
var templateValidator = require('validator').Validator;
connection.validator = new templateValidator();
connection.validator.error = function(msg){ connection.error = msg; };

if(connection.params.limit == null){ connection.params.limit = api.configData.defaultLimit; }
if(connection.params.offset == null){ connection.params.offset = api.configData.defaultOffset; }
if(api.configData.logRequests){api.log("action @ " + connection.remoteIP + " | params: " + JSON.stringify(connection.params));}

if(api.models != null && api.models.log != null){
api.models.log.count({where: ["ip = ? AND createdAt > (NOW() - INTERVAL 1 HOUR)", connection.remoteIP]}).on('success', function(requestThisHourSoFar) {
connection.requestCounter = requestThisHourSoFar + 1;
if(connection.requestCounter <= api.configData.apiRequestLimitPerHour || api.configData.logRequests == false)
{
connection.action = connection.params["action"];
if(api.actions[connection.action] != undefined){
process.nextTick(function() { api.actions[connection.action].run(api, connection, next); });
}else{
if(connection.action == ""){connection.action = "{no action}";}
connection.error = connection.action + " is not a known action.";
process.nextTick(function() { next(connection, true); });
}
}else{
connection.requestCounter = api.configData.apiRequestLimitPerHour;
connection.error = "You have exceded the limit of " + api.configData.apiRequestLimitPerHour + " requests this hour.";
process.nextTick(function() { next(connection, true); });
}
});
}else{
connection.action = connection.params["action"];
if(api.actions[connection.action] != undefined){
process.nextTick(function() { api.actions[connection.action].run(api, connection, next); });
}else{
if(connection.action == ""){connection.action = "{no action}";}
connection.error = connection.action + " is not a known action.";
process.nextTick(function() { next(connection, true); });
}
}
}
}

/////////////////////////////////////////////////////////////////////
// exports
exports.initActions = initActions;
83 changes: 83 additions & 0 deletions initializers/initCache.js
@@ -0,0 +1,83 @@
////////////////////////////////////////////////////////////////////////////
// cache

var initCache = function(api, next){

api.cache = {};

api.cache.buildSQLExpireString = function(api, secondsFromNow){
var now = new Date();
var expireDate = new Date();
expireDate.setTime(now.getTime() + (secondsFromNow * 1000));
var expireDateString = api.utils.sqlDateTime(expireDate);
return expireDateString;
}

api.cache.exists = function(api, key, next){
api.models.cache.count({ where: {key: key} }).on('success', function(num) {
if(num == 1){
process.nextTick(function() { next(true); });
}else{
process.nextTick(function() { next(false); });
}
});
};

api.cache.save = function(api,key,value,expireTimeSeconds,next){
if(expireTimeSeconds < 0 || expireTimeSeconds == null){ expireTimeSeconds = api.configData.cache.defaultExpireTimeSeconds; }
var expireTimeString = api.cache.buildSQLExpireString(api, expireTimeSeconds);
api.cache.exists(api, key, function(exists){
if(exists)
{
api.models.cache.find({ where: {key: key} }).on('success', function(entry) {
if(value == null){value = JSON.parse(entry.value);}
entry.updateAttributes({
value: JSON.stringify(value),
expireTime: expireTimeString
}).on('success', function(){
process.nextTick(function() { next("updated record"); });
});
});
}
else
{
api.models.cache.build({
key: key,
value: JSON.stringify(value),
expireTime: expireTimeString
}).save().on('success', function() {
process.nextTick(function() { next("new record"); });
});
}
});
};

api.cache.load = function(api, key, next){
var nowSQLString = api.utils.sqlDateTime();
api.models.cache.find({ where: ["`key` = ? and expireTime > ?", key, nowSQLString] }).on('success', function(entry) {
if(entry){
var resp = JSON.parse(entry.value);
process.nextTick(function() { next(resp); });
}else{
process.nextTick(function() { next(false); });
}
});
};

api.cache.destroy = function(api, key, next){
api.models.cache.find({ where: {key: key} }).on('success', function(entry) {
if(entry){
entry.destroy();
process.nextTick(function() { next(true); });
}else{
process.nextTick(function() { next(false); });
}
});
};

next();
}

/////////////////////////////////////////////////////////////////////
// exports
exports.initCache = initCache;
36 changes: 36 additions & 0 deletions initializers/initCron.js
@@ -0,0 +1,36 @@
////////////////////////////////////////////////////////////////////////////
// Periodic Tasks (fixed timer events)

var initCron = function(api, next)
{
if (api.configData.cronProcess)
{
api.processCron = function(api){
api.log("* periodic cron tasks starting now *");

// run all tasks every time async
var runningTasks = 0;
for(var task in api.tasks){
if (task != "Task"){
runningTasks++;
api.tasks[task](api, function(){
runningTasks--;
if(runningTasks == 0){
api.log("* periodic cron tasks comple. see you again in " + api.configData.cronTimeInterval + "ms *");
if(api.cronTimer) { clearTimeout(api.cronTimer); }
api.cronTimer = setTimeout(api.processCron, api.configData.cronTimeInterval, api);
}
});
}
}
};

api.cronTimer = setTimeout(api.processCron, api.configData.cronTimeInterval, api);
api.log("periodic (internal cron) interval set to process evey " + api.configData.cronTimeInterval + "ms", "green");
}
next();
}

/////////////////////////////////////////////////////////////////////
// exports
exports.initCron = initCron;
74 changes: 74 additions & 0 deletions initializers/initDB.js
@@ -0,0 +1,74 @@
////////////////////////////////////////////////////////////////////////////
// DB setup

var initDB = function(api, next)
{
if(api.configData.database != null){

var rawDBParams = {
user: api.configData.database.username,
password: api.configData.database.password,
port: api.configData.database.port,
host: api.configData.database.host
};
api.rawDBConnction = api.mysql.createClient(rawDBParams);
api.rawDBConnction.query('USE '+api.configData.database.database, function(e){
if(e){
console.log(" >> error connecting to database, exiting");
console.log(JSON.stringify({database: rawDBParams.database, user: rawDBParams.user, host: rawDBParams.host, port: rawDBParams.port, password: "[censored]"}));
process.exit();
}else{
api.dbObj = new api.SequelizeBase(api.configData.database.database, api.configData.database.username, api.configData.database.password, {
host: api.configData.database.host,
port: api.configData.database.port,
logging: api.configData.database.consoleLogging
});

api.models = {};
api.seeds = {};
api.modelsArray = [];

var modelsPath = process.cwd() + "/models/";
api.path.exists(modelsPath, function (exists) {
if(!exists){
var defaultModelsPath = __dirname + "/models/";
api.log("no ./modles path in project, loading defaults from "+defaultModelsPath, "yellow");
modelsPath = defaultModelsPath;
}

api.fs.readdirSync(modelsPath).forEach( function(file) {
var modelName = file.split(".")[0];
api.models[modelName] = require(modelsPath + file)['defineModel'](api);
api.seeds[modelName] = require(modelsPath + file)['defineSeeds'](api);
api.modelsArray.push(modelName);
api.log("model loaded: " + modelName, "blue");
});
api.dbObj.sync().on('success', function() {
for(var i in api.seeds){
var seeds = api.seeds[i];
var model = api.models[i];
if (seeds != null){
api.utils.DBSeed(api, model, seeds, function(seeded, modelResp){
if(seeded){ api.log("Seeded data for: "+modelResp.name, "cyan"); }
});
}
}
api.log("DB conneciton sucessfull and Objects mapped to DB tables", "green");
next();
}).on('failure', function(error) {
api.log("trouble synchronizing models and DB. Correct DB credentials?", "red");
api.log(JSON.stringify(error));
api.log("exiting", "red");
process.exit();
})
});
}
});
}else{
next();
}
}

/////////////////////////////////////////////////////////////////////
// exports
exports.initDB = initDB;
62 changes: 62 additions & 0 deletions initializers/initLog.js
@@ -0,0 +1,62 @@
////////////////////////////////////////////////////////////////////////////
// logging

var initLog = function(api, next){

try { api.fs.mkdirSync(api.configData.logFolder, "777") } catch(e) {};

api.log = function(original_message, styles){
if(api.configData != null && api.configData.logging == true)
{
// styles is an array of styles
if (styles == null){styles = ["white"];}

if(api.utils != undefined){
var time_string = api.utils.sqlDateTime();
}else{
var time_string = "!";
}

var console_message = api.consoleColors.grey(time_string) + api.consoleColors.grey(" | ");
var inner_message = original_message;
for(var i in styles){
var style = styles[i];
if(style == "bold"){inner_message = api.consoleColors.bold(inner_message);}
else if(style == "italic"){inner_message = api.consoleColors.italic(inner_message);}
else if(style == "underline"){inner_message = api.consoleColors.underline(inner_message);}
else if(style == "inverse"){inner_message = api.consoleColors.inverse(inner_message);}
else if(style == "white"){inner_message = api.consoleColors.white(inner_message);}
else if(style == "grey"){inner_message = api.consoleColors.grey(inner_message);}
else if(style == "black"){inner_message = api.consoleColors.black(inner_message);}
else if(style == "blue"){inner_message = api.consoleColors.blue(inner_message);}
else if(style == "cyan"){inner_message = api.consoleColors.cyan(inner_message);}
else if(style == "green"){inner_message = api.consoleColors.green(inner_message);}
else if(style == "yellow"){inner_message = api.consoleColors.yellow(inner_message);}
else if(style == "red"){inner_message = api.consoleColors.red(inner_message);}
else if(style == "cyan"){inner_message = api.consoleColors.cyan(inner_message);}
else if(style == "magenta"){inner_message = api.consoleColors.magenta(inner_message);}
else if(style == "rainbow"){inner_message = api.consoleColors.rainbow(inner_message);}
else if(style == "black"){inner_message = api.consoleColors.black(inner_message);}
else if(style == "zebra"){inner_message = api.consoleColors.zebra(inner_message);}
else if(style == "zalgo"){inner_message = api.consoleColors.zalgo(inner_message);}
}
console_message += inner_message;
console.log(console_message);
var file_message = time_string + " | " + original_message;
if (api.logWriter == null){
api.logWriter = api.fs.createWriteStream((api.configData.logFolder + "/" + api.configData.logFile), {flags:"a"});
}
try{
api.logWriter.write(file_message + "\r\n");
}catch(e){
console.log(" !!! Error writing to log file: " + e);
}
}
};

next();
}

/////////////////////////////////////////////////////////////////////
// exports
exports.initLog = initLog;

0 comments on commit f8c7385

Please sign in to comment.