Skip to content

Commit

Permalink
Loading hooks services in sandboxed scripts. Fixes #34
Browse files Browse the repository at this point in the history
  • Loading branch information
Pierre-Gilles committed Nov 9, 2015
1 parent e57cdf7 commit 8d5a7bd
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 2 deletions.
66 changes: 64 additions & 2 deletions api/services/ScriptService.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
*/

var vm = require('vm');
var fs = require("fs");
var fs = require('fs');
var path = require('path');

/**
* Description
Expand All @@ -21,6 +22,19 @@ function validFileName (name){
return reg.test(name);
}

/**
* Return true if directory exist
*/
function directoryExist(dirPath){
try{
fs.lstatSync(dirPath).isDirectory();
return true;
}catch(e){
return false;
}

}

/**
* Description
* @method loadInSandbox
Expand All @@ -46,16 +60,64 @@ function loadInSandbox (path, callback){
});
}

function loadHooksServices (name, cb){

var servicePath = path.join(sails.config.scripts.hooksFolder, name, sails.config.scripts.servicesHooksFolder);

// if folder is not a directory, does not exist..
if(!directoryExist(servicePath)){
return cb(null);
}

sails.log.info('Loading services in module ' + name);
sails.log.info('Scanning folder : ' + servicePath);

fs.readdir(servicePath, function (err, files) {
if(err) return cb(err);

for(var key in files){
var file = files[key];
if(validFileName(file)){
file = file.substring(0,file.length-3);
sandbox[file] = global[file];
sails.log.info('Adding service ' + file + ' to sandbox');
delete sandbox[file]['sails'];
}
}
cb(null);
});
}


/**
* Load all services
*/
function loadAllHooksServices (cb){
cb = cb || function() {};

fs.readdir(sails.config.scripts.hooksFolder, function (err, files) {
if(err) return cb(err);

async.each(files, loadHooksServices, cb);
});
}

var sandbox = sails.config.scripts.defaultSandbox;

gladys.on('sailsReady', function(){

// adding sails.log function to sandbox
sandbox.sails = {};
sandbox.sails.log = sails.log;

// adding all the Gladys "api/services" to sandbox
loadInSandbox(sails.config.scripts.servicesFolder, function(err){
if(err) sails.log.warn(err);

});

// adding all the Hooks services to sandbox
loadAllHooksServices(function(err){
if(err) sails.log.warn(err);
});
});

Expand Down
2 changes: 2 additions & 0 deletions config/scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ module.exports.scripts = {
folder:'api/scripts',
servicesFolder: './api/services',
modelFolder: './api/models',
servicesHooksFolder: 'services',
hooksFolder: './api/hooks',
vmOptions:{
},
defaultSandbox: {
Expand Down

0 comments on commit 8d5a7bd

Please sign in to comment.