diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..ff439ef --- /dev/null +++ b/.eslintrc @@ -0,0 +1,33 @@ +{ + "extends": "standard", + "rules": { + "no-multi-spaces": [ + "error", { + "exceptions": { + "Property": true, + "VariableDeclarator": true, + "ImportDeclaration": true + } + } + ], + "key-spacing": [ + "error", { + "align": { + "beforeColon": false, + "afterColon": true, + "on": "value" + }, + "mode": "minimum" + } + ], + "brace-style": ["error", "stroustrup"], + "no-eval": ["error", { + "allowIndirect": true + }], + "semi": ["error", "always"] + }, + "env": { + "node": true, + "mocha": true + } +} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 4535c0c..c9d3f03 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .DS_Store .idea +.vscode node_modules test/.coverage npm-debug.log diff --git a/README.md b/README.md index 92fa492..cbf441a 100644 --- a/README.md +++ b/README.md @@ -94,57 +94,47 @@ See [Examples](./examples) directory ### Releases ## **Current Release** -* 0.5.0 - Release - * Replace Middleware with yanpm plugin manager - * Refactor Service Manager - breaking it into smaller modules - * Custom binary responses - * Examples: - * Auth middleware - Basic +* 0.6.0 - Release + * Service Export + * Added Resource Manager + * Lint Cleanup/Fixes ## Next Release -* 0.6.0 - Polish - * Examples: - * [ ] Auth middleware - * [ ] JWT - * [ ] Passport - * [ ] Error checks (bullet proof) - * [ ] Polish and bug fixes - * [ ] API documentation +* 0.6.x - More Polish + * [ ] Error checks +* 1.0.0 - ES Next! + * [ ] ES6 Classes, decorators + * [ ] General route pipeline + * [ ] Move Express out of the framework to its own plugin (hyper.io-express) + * [ ] API documentation + * [ ] Cleanup/Remove old features not heavily used ## Road Map --- -* 1.0.0 - Release - * [ ] Add $di DI attribute to inject dependencies into a function - * [ ] Move Express out of the framework to its own plugin (hyper.io-express) - * [ ] General route pipeline - * [ ] Input validation +* 1.x.0 - Release + * add Koa support + * Move Service router adapter to plugins and use external repos + * Examples: + * Auth middleware + * JWT + * Passport + * Input validation * Express * https://github.com/ctavan/express-validator * https://github.com/petreboy14/express-joi - -* 1.2.0 - Release - * add Koa support - * Plugin manager support private NPM repos - * Move Service router adapter to plugins and use external repos * Unit Tests * Route Throttling * Express * https://github.com/ivolo/express-rate - * Add CLI - * Keep Alive - * Forever - https://github.com/foreverjs/forever - * PM2 - https://github.com/Unitech/pm2 - -* 1.4.0 - Release * API Doc generation * Express * https://github.com/fliptoo/swagger-express * CLI + * Keep Alive + * Forever - https://github.com/foreverjs/forever + * PM2 - https://github.com/Unitech/pm2 * Add API Doc generation - -* 1.6.0 - Release - * CLI * Create Route for a Controller * Create Basic Server with Service * Build/Package/Deploy @@ -203,6 +193,13 @@ See [Examples](./examples) directory * Sessions * Input +* 0.5.0 - Release + * Replace Middleware with yanpm plugin manager + * Refactor Service Manager - breaking it into smaller modules + * Custom binary responses + * Examples: + * Auth middleware - Basic + ## License [MIT licence information](LICENSE). diff --git a/examples/api/auth-basic/app.js b/examples/api/auth-basic/app.js index 9e3c7d4..9cfc76a 100644 --- a/examples/api/auth-basic/app.js +++ b/examples/api/auth-basic/app.js @@ -5,8 +5,9 @@ var authBasic = require('hyper.io-express-auth-basic'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes @@ -16,27 +17,25 @@ hyper.use(authBasic); // load config and routes var app = hyper.start({ - routes: [ - { - api: "/hello", - required: { - 'auth-basic': { - user: 'hello', - pass: 'world', - message: 'Login with user:"hello" pass:"world"' - } - }, - method: { - get: function world($done) - { - $done( { hello: "world" } ); - } - } + routes: [ + { + api: '/hello', + required: { + 'auth-basic': { + user: 'hello', + pass: 'world', + message: 'Login with user:"hello" pass:"world"' } - ] + }, + method: { + get: function world ($done) { + $done({ hello: 'world' }); + } + } + } + ] }); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/auth-jwt/app.js b/examples/api/auth-jwt/app.js index e071bd8..0cd6ad5 100644 --- a/examples/api/auth-jwt/app.js +++ b/examples/api/auth-jwt/app.js @@ -4,167 +4,168 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes var hyper = new Hyper(options); - // -function authJWT(_config) { - this._config = _config; - this.handles = ['authRequired', 'authLogin']; +function authJWT (_config) { + this._config = _config; + this.handles = ['authRequired', 'authLogin']; } -authJWT.prototype.init = function(_logger, _httpFramework, _middleware, _serviceManager) { - this._logger = _logger; - this._serviceManager = _serviceManager; - this._middleware = _middleware; - this._httpFramework = _httpFramework; +authJWT.prototype.init = function (_logger, _httpFramework, _middleware, _serviceManager) { + this._logger = _logger; + this._serviceManager = _serviceManager; + this._middleware = _middleware; + this._httpFramework = _httpFramework; - this._secret = "keyboard cat"; + this._secret = 'keyboard cat'; - this._jwt = require('jsonwebtoken'); + this._jwt = require('jsonwebtoken'); }; -authJWT.prototype.setup = function(handleKey, defaultConfig, service, controller, route) { +authJWT.prototype.setup = function (handleKey, defaultConfig, service, controller, route) { + var method = null; + var func = null; - function getToken(req) { - if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { - return req.headers.authorization.split(' ')[1]; - } else if (req.query && req.query.token) { - return req.query.token; - } - return null; + function getToken (req) { + if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { + return req.headers.authorization.split(' ')[1]; + } + else if (req.query && req.query.token) { + return req.query.token; } + return null; + } - if( route.hasOwnProperty('api') && + if (route.hasOwnProperty('api') && handleKey === 'authLogin' && defaultConfig === true) { - this._logger.log('Enable Auth Login for Route:', route.api); + this._logger.log('Enable Auth Login for Route:', route.api); - if(!route.resolve) { - route.resolve = {}; - } + if (!route.resolve) { + route.resolve = {}; + } - //TODO: needs to be a factory instead of value DI + // TODO: needs to be a factory instead of value DI // authData should be instance per request - var authData = { - user: {}, - authenticated: false - }; - route.resolve['$auth'] = function() { - return authData; - }; + var authData = { + user: {}, + authenticated: false + }; + route.resolve['$auth'] = function () { + return authData; + }; - for(var method in route.method) { - var func = route.method[method]; + for (method in route.method) { + func = route.method[method]; // TODO: needs to make this generic (NOT express specific) - this._httpFramework.app()[method]( + this._httpFramework.app()[method]( route.api, func, - function(req, res, next){ - var token = this._jwt.sign(authData, this._secret, { - expiresIn: 60*60*5 - }); - - res.json({ - token: token - }); + function (req, res, next) { + var token = this._jwt.sign(authData, this._secret, { + expiresIn: 60 * 60 * 5 + }); + + res.json({ + token: token + }); }.bind(this) ); - } } - else if( route.hasOwnProperty('api') && + } + else if (route.hasOwnProperty('api') && handleKey === 'authRequired' && defaultConfig === true) { - this._logger.log('Enable Auth for Route:', route.api); + this._logger.log('Enable Auth for Route:', route.api); - for(var method in route.method) { - var func = route.method[method]; + for (method in route.method) { + func = route.method[method]; // TODO: needs to make this generic (NOT express specific) - this._httpFramework.app()[method]( + this._httpFramework.app()[method]( route.api, - function(req, res, next){ - console.log('auth before'); + function (req, res, next) { + console.log('auth before'); // TODO validate token - var token = getToken(req); - if(token !== null) { - this._jwt.verify(token, this._secret, function(err, decoded) { - if(!err) { + var token = getToken(req); + if (token !== null) { + this._jwt.verify(token, this._secret, function (err, decoded) { + if (!err) { // TODO decode data should set the DI auth value for the next // TODO DI breaks here - func(req, res, next); - } else { - res.end('invalid token'); - } - }.bind(this)); - } else { - res.end("error"); - } + func(req, res, next); + } + else { + res.end('invalid token'); + } + }); + } + else { + res.end('error'); + } }.bind(this) ); - } } + } }; -hyper.middleware(authJWT, {secret: 'keyboard kat'} ); +hyper.middleware(authJWT, {secret: 'keyboard kat'}); // load config and routes var app = hyper.start({ - routes: [ - { - api: "/secure", - authRequired: true, - method: { - get: function secure(req, res, next, $done) - { - // TODO DI is not passing through need to fix this - //$done( { secure: "world" } ); - res.json( { secure: "world" } ); - } - } - }, - { - api: "/login", - authLogin: true, - method: { - post: function login($input, $auth, $next, $error) - { - if( $input.body.user === 'test' && - $input.body.pass === '123' ) { - - $auth.authenticated = true; - $auth.user = { - group: 'admin' - }; + routes: [ + { + api: '/secure', + authRequired: true, + method: { + get: function secure (req, res, next, $done) { + // TODO DI is not passing through need to fix this + // $done( { secure: "world" } ); + res.json({ secure: 'world' }); + } + } + }, + { + api: '/login', + authLogin: true, + method: { + post: function login ($input, $auth, $next, $error) { + if ($input.body.user === 'test' && + $input.body.pass === '123') { + $auth.authenticated = true; + $auth.user = { + group: 'admin' + }; // TODO fix this, the data should flow down the pipeline - $next(); - } else { - $error( { "error": "invalid user/pass" } ); - } - } - } - }, - { - api: "/hello", - method: { - get: function hello($done) - { - $done( { notSecret: "hello" } ); - } - } + $next(); + } + else { + $error({ 'error': 'invalid user/pass' }); + } + } + } + }, + { + api: '/hello', + method: { + get: function hello ($done) { + $done({ notSecret: 'hello' }); } - ] + } + } + ] }); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/es6-decorator-route-multifile/app.js b/examples/api/es6-decorator-route-multifile/app.js index 5fc9694..3df08ad 100644 --- a/examples/api/es6-decorator-route-multifile/app.js +++ b/examples/api/es6-decorator-route-multifile/app.js @@ -4,17 +4,16 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! - // Load's config files then // Start web server var hyper = new Hyper(options); var app = hyper.start(); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/es6-decorator-route-multifile/controllers/hello.js b/examples/api/es6-decorator-route-multifile/controllers/hello.js index 791f90a..fe199a2 100644 --- a/examples/api/es6-decorator-route-multifile/controllers/hello.js +++ b/examples/api/es6-decorator-route-multifile/controllers/hello.js @@ -2,34 +2,35 @@ var Hyper = require('../../../../index.js'); class HelloCtrl extends Hyper.classes.controller { - constructor($logger) { - this.logger = $logger; - } - - // Future JSNext - // @Hyper.decor.route({ - // api: { - // route: '/hello', - // method: ['get'] - // } - // }) - hello($done) { - /*@Hyper.route({ + constructor ($logger) { + super($logger); + this.logger = $logger; + } + + // Future JSNext + // @Hyper.decor.route({ + // api: { + // route: '/hello', + // method: ['get'] + // } + // }) + hello ($done) { + /* @Hyper.route({ "api": "/hello", "method": ["get"] - })*/ + }) */ - $done({ hello: "world1" }); - } + $done({ hello: 'world1' }); + } - world($done){ - //@Hyper.route({ + world ($done) { + // @Hyper.route({ // "api": "/world", // "method": ["get"] - //}) + // }) - $done({ hello: "world2" }); - } + $done({ hello: 'world2' }); + } } @@ -38,12 +39,12 @@ module.exports = HelloCtrl; // // -//function MyController2() { -//} -//Hyper.util.extends(MyController2, Hyper.classes.controller); -//// +// function MyController2() { +// } +// Hyper.util.extends(MyController2, Hyper.classes.controller); +// // // -//MyController2.prototype.handler2 = function($done){ +// MyController2.prototype.handler2 = function($done){ // /*@Hyper.handler({ // "api": { // "route": "/hello2", @@ -52,5 +53,5 @@ module.exports = HelloCtrl; // })*/ // // $done({hello:'world 2'}); -//} +// } diff --git a/examples/api/es6-generator-multifile/app.js b/examples/api/es6-generator-multifile/app.js index 5fc9694..3df08ad 100644 --- a/examples/api/es6-generator-multifile/app.js +++ b/examples/api/es6-generator-multifile/app.js @@ -4,17 +4,16 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! - // Load's config files then // Start web server var hyper = new Hyper(options); var app = hyper.start(); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/es6-generator-multifile/app.routes.js b/examples/api/es6-generator-multifile/app.routes.js index 1882c63..1ce8292 100644 --- a/examples/api/es6-generator-multifile/app.routes.js +++ b/examples/api/es6-generator-multifile/app.routes.js @@ -1,18 +1,18 @@ // Routes module.exports = [ - { - api: "/hello", - controller: "main", // default "/controllers/.js" - method: { - get: "hello" // defined in controller module" - } - }, - { - api: "/world", - controller: "main", // default "/controllers/.js" - method: { - get: "world" // defined in controller module" - } + { + api: '/hello', + controller: 'main', // default "/controllers/.js" + method: { + get: 'hello' // defined in controller module" } + }, + { + api: '/world', + controller: 'main', // default "/controllers/.js" + method: { + get: 'world' // defined in controller module" + } + } ]; diff --git a/examples/api/es6-generator-multifile/controllers/main.js b/examples/api/es6-generator-multifile/controllers/main.js index f6063f1..befec4a 100644 --- a/examples/api/es6-generator-multifile/controllers/main.js +++ b/examples/api/es6-generator-multifile/controllers/main.js @@ -1,40 +1,38 @@ 'use strict'; -function promiseDelay($q, func) { - var deferer = $q.defer(); +function promiseDelay ($q, func) { + var deferer = $q.defer(); - setTimeout(function(){ - deferer.resolve( func() ); - }, 50); + setTimeout(function () { + deferer.resolve(func()); + }, 50); - return deferer.promise; + return deferer.promise; } class HelloCtrl { - constructor($logger) { - this.logger = $logger; - } + constructor ($logger) { + this.logger = $logger; + } // localhost:8000/hello - hello($done, $q) - { - this.logger.info('/hello - defer request with timeout'); - return promiseDelay($q, function(){ - return { hello: "world promise" }; - }); - } + hello ($done, $q) { + this.logger.info('/hello - defer request with timeout'); + return promiseDelay($q, function () { + return { hello: 'world promise' }; + }); + } // localhost:8000/world - * world($done, $q) - { - this.logger.info('/world - yielded request with timeout'); + * world ($done, $q) { + this.logger.info('/world - yielded request with timeout'); - var data = yield promiseDelay($q, function(){ - return { hello: "world yield" }; - }); + var data = yield promiseDelay($q, function () { + return { hello: 'world yield' }; + }); - $done( data ); - } + $done(data); + } } // node 4/5 does not support export class diff --git a/examples/api/es6-generator-singlefile/app.js b/examples/api/es6-generator-singlefile/app.js index 9708929..f08570e 100644 --- a/examples/api/es6-generator-singlefile/app.js +++ b/examples/api/es6-generator-singlefile/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes @@ -13,32 +14,30 @@ var hyper = new Hyper(options); var app = hyper .start({ - routes: [ - { - api: "/hello", - method: { - get: function* world($done, $q) - { - var deferer = $q.defer(); - setTimeout(function(){ - deferer.resolve({ hello: "world" }); - }, 500); + routes: [ + { + api: '/hello', + method: { + get: function* world ($done, $q) { + var deferer = $q.defer(); + setTimeout(function () { + deferer.resolve({ hello: 'world' }); + }, 500); - var data = yield deferer.promise; + var data = yield deferer.promise; - //$done( data ); - // OR - return data; - } - } + // $done( data ); + // OR + return data; } - ] - }).then(function(server){ - server.logger().log("Server Started"); - return server; + } + } + ] + }).then(function (server) { + server.logger().log('Server Started'); + return server; }); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/es6-helloworld-multifile/app.js b/examples/api/es6-helloworld-multifile/app.js index 5fc9694..3df08ad 100644 --- a/examples/api/es6-helloworld-multifile/app.js +++ b/examples/api/es6-helloworld-multifile/app.js @@ -4,17 +4,16 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! - // Load's config files then // Start web server var hyper = new Hyper(options); var app = hyper.start(); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/es6-helloworld-multifile/app.routes.js b/examples/api/es6-helloworld-multifile/app.routes.js index 01958a0..8b8b1a7 100644 --- a/examples/api/es6-helloworld-multifile/app.routes.js +++ b/examples/api/es6-helloworld-multifile/app.routes.js @@ -1,11 +1,11 @@ // Routes module.exports = [ - { - api: "/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "hello" // defined in controller module" - } + { + api: '/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'hello' // defined in controller module" } + } ]; diff --git a/examples/api/es6-helloworld-multifile/controllers/hello.js b/examples/api/es6-helloworld-multifile/controllers/hello.js index acdecc7..993c656 100644 --- a/examples/api/es6-helloworld-multifile/controllers/hello.js +++ b/examples/api/es6-helloworld-multifile/controllers/hello.js @@ -1,15 +1,14 @@ 'use strict'; class HelloCtrl { - constructor($logger) { - this.logger = $logger; - } + constructor ($logger) { + this.logger = $logger; + } - // localhost:8000/hello - hello($done) - { - $done({ hello: "world" }); - } + // localhost:8000/hello + hello ($done) { + $done({ hello: 'world' }); + } } // node 4/5 does not support export class diff --git a/examples/api/es6-prepost-route-multifile/app.js b/examples/api/es6-prepost-route-multifile/app.js index 5fc9694..3df08ad 100644 --- a/examples/api/es6-prepost-route-multifile/app.js +++ b/examples/api/es6-prepost-route-multifile/app.js @@ -4,17 +4,16 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! - // Load's config files then // Start web server var hyper = new Hyper(options); var app = hyper.start(); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/es6-prepost-route-multifile/app.routes.js b/examples/api/es6-prepost-route-multifile/app.routes.js index 01958a0..8b8b1a7 100644 --- a/examples/api/es6-prepost-route-multifile/app.routes.js +++ b/examples/api/es6-prepost-route-multifile/app.routes.js @@ -1,11 +1,11 @@ // Routes module.exports = [ - { - api: "/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "hello" // defined in controller module" - } + { + api: '/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'hello' // defined in controller module" } + } ]; diff --git a/examples/api/es6-prepost-route-multifile/controllers/hello.js b/examples/api/es6-prepost-route-multifile/controllers/hello.js index 0bda698..9e47954 100644 --- a/examples/api/es6-prepost-route-multifile/controllers/hello.js +++ b/examples/api/es6-prepost-route-multifile/controllers/hello.js @@ -1,57 +1,55 @@ 'use strict'; class HelloCtrl { - constructor($logger) { - this.data = { hello: "world" }; - this.logger = $logger; + constructor ($logger) { + this.data = { hello: 'world' }; + this.logger = $logger; + } + + // support all the same features as handles + // (eg, generators, promises, throw errors...) + $preRoute ($input, $error, $q) { + if (!$input.query || !$input.query.q) { + // TODO: support throwing errors + $error('missing search input', 404); + /* + throw new Error({ + errorCode: 404, + errorMsg: 'missing search input' + }); + */ } - - // support all the same features as handles - // (eg, generators, promises, throw errors...) - $preRoute($input, $error, $q){ - if(!$input.query || !$input.query.q) { - // TODO: support throwing errors - $error('missing search input', 404); - /* - throw new Error({ - errorCode: 404, - errorMsg: 'missing search input' - }); - */ - } else { - // can return promise, like handler - return $q.resolve({ - pre: $input.query.q, - data: this.data - }); - } + else { + // can return promise, like handler + return $q.resolve({ + pre: $input.query.q, + data: this.data + }); } - - // not called if error thown - $postRoute($output) { - - if($output.code > 399) { - - var errorMsg = $output.data; - $output.data = { - errorMsg: errorMsg, - errorCode: $output.code - } - - } else { - // can return data, like handler - $output.data.post = 'test2'; - } - - return $output; + } + + // not called if error thown + $postRoute ($output) { + if ($output.code > 399) { + var errorMsg = $output.data; + $output.data = { + errorMsg: errorMsg, + errorCode: $output.code + }; } - - // localhost:8000/hello - hello($done, $output) - { - $output.data.hello = 'test hello'; - return $output; + else { + // can return data, like handler + $output.data.post = 'test2'; } + + return $output; + } + + // localhost:8000/hello + hello ($done, $output) { + $output.data.hello = 'test hello'; + return $output; + } } // node 4/5 does not support export class diff --git a/examples/api/externalservice-basic/app.js b/examples/api/externalservice-basic/app.js index e09a3d3..b1c82c9 100755 --- a/examples/api/externalservice-basic/app.js +++ b/examples/api/externalservice-basic/app.js @@ -1,115 +1,120 @@ 'use strict'; var Hyper = require('../../../index.js'); var when = require('when/node'); -var freeport = when.lift( require('freeport') ); +var freeport = when.lift(require('freeport')); // !-- FOR TESTS var options1 = {}; try { - options1 = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options1 = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // load config and routes var hyper1 = new Hyper(options1); hyper1.load({ - services: { - "service1": { - routes: [{ - api: "/service1/hello", - method: { - get: function hello($done, $services) - { - $services.find('service2') - .get('/service2/world', { query: { hello: 'world1'} }) - .then(function(data){ - $done( data ); - }); - } + services: { + 'service1': { + routes: [{ + api: '/service1/hello', + method: { + get: function hello ($done, $services) { + $services.find('service2') + .get('/service2/world', { + query: { + hello: 'world1' } - }] - }, - "service2": { - routes: [{ - api: "/service2/hello", - method: { - get: function hello($done, $services) - { - $services.find('service3') - .get('/service3/world', { query: { hello: 'world2'} } ) - .then(function(data){ - $done( data ); - }); - } + }) + .then(function (data) { + $done(data); + }); + } + } + }] + }, + 'service2': { + routes: [{ + api: '/service2/hello', + method: { + get: function hello ($done, $services) { + $services.find('service3') + .get('/service3/world', { + query: { + hello: 'world2' } - }, - { - api: "/service2/world", - method: { - get: function world($done, $logger, $input) - { - var data = { - hello2: $input.query.hello, - ts: new Date() - }; - $logger.log('world2 data:', data); + }) + .then(function (data) { + $done(data); + }); + } + } + }, + { + api: '/service2/world', + method: { + get: function world ($done, $logger, $input) { + var data = { + hello2: $input.query.hello, + ts: new Date() + }; + $logger.log('world2 data:', data); - $done( data ); - } - } - }] + $done(data); + } } + }] } + } }); var app1 = hyper1.start(); -app1.then(function() { - return freeport().then(function(port) { - // server3 options - var options2 = { - port: port, - silent: true - }; +app1.then(function () { + return freeport().then(function (port) { + // server3 options + var options2 = { + port: port, + silent: true + }; - hyper1.services().add({ - name: 'service3', - adapter: 'http', // can be a object, for custom adapters - options: { - hostname: '127.0.0.1', - port: options2.port - } - }); + hyper1.services().add({ + name: 'service3', + adapter: 'http', // can be a object, for custom adapters + options: { + hostname: '127.0.0.1', + port: options2.port + } + }); - // load config and routes - var hyper2 = new Hyper(options2); + // load config and routes + var hyper2 = new Hyper(options2); - var app2 = hyper2.start({ - services: { - "service3": { - routes: [{ - api: "/service3/world", - method: { - get: function hello($done, $input) - { - var data = { - hello3: $input.query.hello, - ts: new Date() - }; - $done( data ); - } - } - }] - } + var app2 = hyper2.start({ + services: { + 'service3': { + routes: [{ + api: '/service3/world', + method: { + get: function hello ($done, $input) { + var data = { + hello3: $input.query.hello, + ts: new Date() + }; + $done(data); + } } - }); + }] + } + } + }); - return app2.then(function(){ - // need to pass hyper back so tess will work - return hyper1; - }); + return app2.then(function () { + // need to pass hyper back so tess will work + return hyper1; }); + }); }); // !-- FOR TESTS diff --git a/examples/api/externalservice-websockets/app.js b/examples/api/externalservice-websockets/app.js index 62be27c..8a5937c 100755 --- a/examples/api/externalservice-websockets/app.js +++ b/examples/api/externalservice-websockets/app.js @@ -1,13 +1,14 @@ 'use strict'; var Hyper = require('../../../index.js'); var when = require('when/node'); -var freeport = when.lift( require('freeport') ); +var freeport = when.lift(require('freeport')); // !-- FOR TESTS var options1 = {}; try { - options1 = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options1 = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // load config and routes @@ -17,32 +18,32 @@ var hyper1 = new Hyper(options1); // Start web server var app1 = hyper1.start(['service1', 'service2']); -app1.then(function() { - return freeport().then(function (port) { +app1.then(function () { + return freeport().then(function (port) { // server3 options - var options2 = { - port: port, - silent: true - }; - - hyper1.services().add({ - name: 'wsService', - adapter: 'http', // can be a object, for custom adapters - options: { - hostname: 'localhost', - port: options2.port - } - }); + var options2 = { + port: port, + silent: true + }; + + hyper1.services().add({ + name: 'wsService', + adapter: 'http', // can be a object, for custom adapters + options: { + hostname: 'localhost', + port: options2.port + } + }); // load config and routes - var hyper2 = new Hyper(options2); - var app2 = hyper2.start(['wsService']); + var hyper2 = new Hyper(options2); + var app2 = hyper2.start(['wsService']); - return app2.then(function(){ + return app2.then(function () { // need to pass hyper back so tess will work - return hyper1; - }); + return hyper1; }); + }); }); // !-- FOR TESTS diff --git a/examples/api/externalservice-websockets/service1/controllers/hello.js b/examples/api/externalservice-websockets/service1/controllers/hello.js index a06cf2a..e71471e 100755 --- a/examples/api/externalservice-websockets/service1/controllers/hello.js +++ b/examples/api/externalservice-websockets/service1/controllers/hello.js @@ -2,16 +2,19 @@ module.exports = HelloCtrl; -function HelloCtrl($logger){ - $logger.log('Service 1 - Hello Ctrl Init'); +function HelloCtrl ($logger) { + $logger.log('Service 1 - Hello Ctrl Init'); } // localhost:8000/service1/hello -HelloCtrl.prototype.hello = function($done, $services) -{ - $services.find('service2') - .get('/service2/world', { query: { hello: 'world1'} }) - .then(function(data){ - $done( data ); - }); +HelloCtrl.prototype.hello = function ($done, $services) { + $services.find('service2') + .get('/service2/world', { + query: { + hello: 'world1' + } + }) + .then(function (data) { + $done(data); + }); }; diff --git a/examples/api/externalservice-websockets/service1/service1.js b/examples/api/externalservice-websockets/service1/service1.js index 66cbff3..b3b6673 100644 --- a/examples/api/externalservice-websockets/service1/service1.js +++ b/examples/api/externalservice-websockets/service1/service1.js @@ -1,6 +1,6 @@ module.exports = Service1; -function Service1($logger){ - $logger.log('Service 1 - Init'); +function Service1 ($logger) { + $logger.log('Service 1 - Init'); } diff --git a/examples/api/externalservice-websockets/service1/service1.routes.js b/examples/api/externalservice-websockets/service1/service1.routes.js index 11ee15c..20deaac 100644 --- a/examples/api/externalservice-websockets/service1/service1.routes.js +++ b/examples/api/externalservice-websockets/service1/service1.routes.js @@ -1,14 +1,14 @@ // Routes module.exports = [ - { - api: "/service1/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "hello" // defined in controller module" - } - }, - { - static: 'static' + { + api: '/service1/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'hello' // defined in controller module" } + }, + { + static: 'static' + } ]; diff --git a/examples/api/externalservice-websockets/service2/controllers/hello.js b/examples/api/externalservice-websockets/service2/controllers/hello.js index 5334424..e79e473 100755 --- a/examples/api/externalservice-websockets/service2/controllers/hello.js +++ b/examples/api/externalservice-websockets/service2/controllers/hello.js @@ -2,28 +2,31 @@ module.exports = HelloCtrl; -function HelloCtrl($logger){ - $logger.log('Service 2 - Hello Ctrl Init'); +function HelloCtrl ($logger) { + $logger.log('Service 2 - Hello Ctrl Init'); } // localhost:8000/service2/hello -HelloCtrl.prototype.hello = function($done, $services) -{ - // send message to WebSocket service - $services.find('wsService') - .get('/ws/event/update', { query: { hello: 'wsService', ts1: (new Date()).getTime()} } ) - .then(function(data){ - $done( data ); - }); +HelloCtrl.prototype.hello = function ($done, $services) { + // send message to WebSocket service + $services.find('wsService') + .get('/ws/event/update', { + query: { + hello: 'wsService', + ts1: (new Date()).getTime() + } + }) + .then(function (data) { + $done(data); + }); }; // localhost:8000/service2/world -HelloCtrl.prototype.world = function($done, $input) -{ - var data = { - hello2: $input.query.hello, - ts: new Date() - }; +HelloCtrl.prototype.world = function ($done, $input) { + var data = { + hello2: $input.query.hello, + ts: new Date() + }; - $done( data ); + $done(data); }; diff --git a/examples/api/externalservice-websockets/service2/service2.js b/examples/api/externalservice-websockets/service2/service2.js index 6ed2630..fbd88d0 100644 --- a/examples/api/externalservice-websockets/service2/service2.js +++ b/examples/api/externalservice-websockets/service2/service2.js @@ -1,6 +1,6 @@ module.exports = Service2; -function Service2($logger){ - $logger.log('Service 2 - Init'); +function Service2 ($logger) { + $logger.log('Service 2 - Init'); } diff --git a/examples/api/externalservice-websockets/service2/service2.routes.js b/examples/api/externalservice-websockets/service2/service2.routes.js index 272ecfc..2ba525a 100644 --- a/examples/api/externalservice-websockets/service2/service2.routes.js +++ b/examples/api/externalservice-websockets/service2/service2.routes.js @@ -1,18 +1,18 @@ // Routes module.exports = [ - { - api: "/service2/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "hello" // defined in controller module" - } - }, - { - api: "/service2/world", - controller: "hello", // default "/controllers/.js" - method: { - get: "world" // defined in controller module" - } + { + api: '/service2/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'hello' // defined in controller module" } + }, + { + api: '/service2/world', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'world' // defined in controller module" + } + } ]; diff --git a/examples/api/externalservice-websockets/wsService/controllers/event.js b/examples/api/externalservice-websockets/wsService/controllers/event.js index ae82cdf..0bf5863 100644 --- a/examples/api/externalservice-websockets/wsService/controllers/event.js +++ b/examples/api/externalservice-websockets/wsService/controllers/event.js @@ -2,16 +2,15 @@ module.exports = EventCtrl; -function EventCtrl($logger){ - $logger.log('Event Ctrl Init'); +function EventCtrl ($logger) { + $logger.log('Event Ctrl Init'); } // localhost:12003/ws/event/update -EventCtrl.prototype.update = function($done, $logger, $service, $input) -{ +EventCtrl.prototype.update = function ($done, $logger, $service, $input) { // TODO: push message up web socket - $logger.log('update - $input.query:', $input.query); - $service.sendEvent($input.query); + $logger.log('update - $input.query:', $input.query); + $service.sendEvent($input.query); - $done( { statusCode: 200 } ); + $done({ statusCode: 200 }); }; diff --git a/examples/api/externalservice-websockets/wsService/wsService.js b/examples/api/externalservice-websockets/wsService/wsService.js index 1f5f236..591721e 100644 --- a/examples/api/externalservice-websockets/wsService/wsService.js +++ b/examples/api/externalservice-websockets/wsService/wsService.js @@ -1,40 +1,37 @@ module.exports = wsService; -var logger = null; var socket = require('socket.io'); -function wsService($logger, $hyper){ - logger = $logger; - $logger.log('Init'); +function wsService ($logger, $hyper) { + $logger.log('Init'); // init socket.io - this.io = socket( $hyper.httpServer() ); - this._connections = []; + this.io = socket($hyper.httpServer()); + this._connections = []; - this.io.on('connection', function (socket) { - this._connections.push(socket); - }.bind(this)); + this.io.on('connection', function (socket) { + this._connections.push(socket); + }.bind(this)); // Add headers so client can connect to this service - $hyper.httpFramework() + $hyper.httpFramework() .app() .use(function (req, res, next) { - res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000'); - res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); - res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); - res.setHeader('Access-Control-Allow-Credentials', true); - next(); + res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000'); + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); + res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); + res.setHeader('Access-Control-Allow-Credentials', true); + next(); }); } -wsService.prototype.sendEvent = function(event) { - event.ts1 = parseInt(event.ts1); - event.ts2 = (new Date()).getTime(); - event.tsDiff = event.ts2 - event.ts1; - //logger.log('sendEvent:', event); +wsService.prototype.sendEvent = function (event) { + event.ts1 = parseInt(event.ts1); + event.ts2 = (new Date()).getTime(); + event.tsDiff = event.ts2 - event.ts1; - for(var i = 0; i < this._connections.length; i++) { - this._connections[i].emit('event', event); - } + for (var i = 0; i < this._connections.length; i++) { + this._connections[i].emit('event', event); + } }; diff --git a/examples/api/externalservice-websockets/wsService/wsService.routes.js b/examples/api/externalservice-websockets/wsService/wsService.routes.js index 366afc3..f4d9149 100644 --- a/examples/api/externalservice-websockets/wsService/wsService.routes.js +++ b/examples/api/externalservice-websockets/wsService/wsService.routes.js @@ -1,11 +1,11 @@ // Internet Service Routes module.exports = [ - { - api: "/ws/event/update", - controller: "event", // default "/controllers/.js" - method: { - get: "update" // defined in controller module" - } + { + api: '/ws/event/update', + controller: 'event', // default "/controllers/.js" + method: { + get: 'update' // defined in controller module" } + } ]; diff --git a/examples/api/helloworld-custompath/custom_path/app.js b/examples/api/helloworld-custompath/custom_path/app.js index 9e86705..208645c 100644 --- a/examples/api/helloworld-custompath/custom_path/app.js +++ b/examples/api/helloworld-custompath/custom_path/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load's config files @@ -13,8 +14,8 @@ var hyper = new Hyper(options); // load routes var app = hyper.start({ - name: "app", - directory: "custom_path" + name: 'app', + directory: 'custom_path' }); // !-- FOR TESTS diff --git a/examples/api/helloworld-custompath/custom_path/app.routes.js b/examples/api/helloworld-custompath/custom_path/app.routes.js index e0d9d25..24e83c0 100644 --- a/examples/api/helloworld-custompath/custom_path/app.routes.js +++ b/examples/api/helloworld-custompath/custom_path/app.routes.js @@ -1,11 +1,11 @@ // Routes module.exports = [ - { - api: "/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "world" // defined in controller module" - } + { + api: '/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'world' // defined in controller module" } + } ]; diff --git a/examples/api/helloworld-custompath/custom_path/controllers/hello.js b/examples/api/helloworld-custompath/custom_path/controllers/hello.js index 94a5172..46a0132 100644 --- a/examples/api/helloworld-custompath/custom_path/controllers/hello.js +++ b/examples/api/helloworld-custompath/custom_path/controllers/hello.js @@ -2,11 +2,10 @@ module.exports = HelloCtrl; -function HelloCtrl(){ +function HelloCtrl () { } // localhost:8000/hello -HelloCtrl.prototype.world = function($done) -{ - $done( { hello: "world" } ); +HelloCtrl.prototype.world = function ($done) { + $done({ hello: 'world' }); }; diff --git a/examples/api/helloworld-multifile/app.js b/examples/api/helloworld-multifile/app.js index 5fc9694..3df08ad 100644 --- a/examples/api/helloworld-multifile/app.js +++ b/examples/api/helloworld-multifile/app.js @@ -4,17 +4,16 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! - // Load's config files then // Start web server var hyper = new Hyper(options); var app = hyper.start(); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/helloworld-multifile/app.routes.js b/examples/api/helloworld-multifile/app.routes.js index 5ca7c58..7eb7875 100644 --- a/examples/api/helloworld-multifile/app.routes.js +++ b/examples/api/helloworld-multifile/app.routes.js @@ -1,18 +1,18 @@ // Routes module.exports = [ - { - api: "/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "hello" // defined in controller module" - } - }, - { - api: "/world", - controller: "hello", // default "/controllers/.js" - method: { - get: "world" // defined in controller module" - } + { + api: '/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'hello' // defined in controller module" } + }, + { + api: '/world', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'world' // defined in controller module" + } + } ]; diff --git a/examples/api/helloworld-multifile/controllers/hello.js b/examples/api/helloworld-multifile/controllers/hello.js index 816cf8c..7bd3ffb 100644 --- a/examples/api/helloworld-multifile/controllers/hello.js +++ b/examples/api/helloworld-multifile/controllers/hello.js @@ -2,18 +2,16 @@ module.exports = HelloCtrl; -function HelloCtrl(){ - this.data = { hello: "world" }; +function HelloCtrl () { + this.data = { hello: 'world' }; } // localhost:8000/hello -HelloCtrl.prototype.hello = function($done) -{ - $done( this.data ); +HelloCtrl.prototype.hello = function ($done) { + $done(this.data); }; // localhost:8000/world -HelloCtrl.prototype.world = function() -{ - return this.data; +HelloCtrl.prototype.world = function () { + return this.data; }; diff --git a/examples/api/helloworld-preroute/app.js b/examples/api/helloworld-preroute/app.js index 5303403..4f2591c 100644 --- a/examples/api/helloworld-preroute/app.js +++ b/examples/api/helloworld-preroute/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes @@ -13,31 +14,28 @@ var hyper = new Hyper(options); var app = hyper .start({ - preRoutes: function ($http, $logger) + preRoutes: function ($http, $logger) { + $logger.log('Ran preRoutes'); + $http.app().use(function (req, res, next) { + $logger.log('custom test'); + next(); + }); + }, + routes: [ { - $logger.log('Ran preRoutes'); - $http.app().use(function(req, res, next){ - $logger.log('custom test'); - next(); - }); - }, - routes: [ - { - api: "/hello", - method: { - get: function world($done) - { - $done( { hello: "world" } ); - } - } + api: '/hello', + method: { + get: function world ($done) { + $done({ hello: 'world' }); } - ] - }).then(function(server){ - server.logger().log("Server Started"); - return server; + } + } + ] + }).then(function (server) { + server.logger().log('Server Started'); + return server; }); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/helloworld-singlefile/app.js b/examples/api/helloworld-singlefile/app.js index 670c950..5db113e 100644 --- a/examples/api/helloworld-singlefile/app.js +++ b/examples/api/helloworld-singlefile/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes @@ -13,23 +14,21 @@ var hyper = new Hyper(options); var app = hyper .start({ - routes: [ - { - api: "/hello", - method: { - get: function world($done) - { - $done( { hello: "world" } ); - } - } + routes: [ + { + api: '/hello', + method: { + get: function world ($done) { + $done({ hello: 'world' }); } - ] - }).then(function(server){ - server.logger().log("Server Started"); - return server; + } + } + ] + }).then(function (server) { + server.logger().log('Server Started'); + return server; }); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/input-basic/app.js b/examples/api/input-basic/app.js index 02c4dc9..3918557 100644 --- a/examples/api/input-basic/app.js +++ b/examples/api/input-basic/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes @@ -13,42 +14,38 @@ var hyper = new Hyper(options); var app = hyper .start({ - routes: [ - { - api: "/hello", - method: { - get: function helloGet($done, $input) - { - $done( { - hello: $input.query - } ); - }, - post: function helloPost($done, $input) - { - $done( { - hello: $input.body - } ); - } - } + routes: [ + { + api: '/hello', + method: { + get: function helloGet ($done, $input) { + $done({ + hello: $input.query + }); }, - { - api: "/world/:worldName", - method: { - get: function world($done, $input) - { - $done( { - world: $input.params.worldName - } ); - } - } + post: function helloPost ($done, $input) { + $done({ + hello: $input.body + }); } - ] - }).then(function(server){ - server.logger().log("Server Started"); - return server; + } + }, + { + api: '/world/:worldName', + method: { + get: function world ($done, $input) { + $done({ + world: $input.params.worldName + }); + } + } + } + ] + }).then(function (server) { + server.logger().log('Server Started'); + return server; }); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/multiservice-multifile/app.js b/examples/api/multiservice-multifile/app.js index 55ef1a4..cb0dbd9 100644 --- a/examples/api/multiservice-multifile/app.js +++ b/examples/api/multiservice-multifile/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // load config and routes @@ -14,7 +15,6 @@ var hyper = new Hyper(options); // Start web server var app = hyper.start(['service1', 'service2']); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/multiservice-multifile/service1/controllers/hello.js b/examples/api/multiservice-multifile/service1/controllers/hello.js index 81b4000..195975a 100644 --- a/examples/api/multiservice-multifile/service1/controllers/hello.js +++ b/examples/api/multiservice-multifile/service1/controllers/hello.js @@ -2,12 +2,11 @@ module.exports = HelloCtrl; -function HelloCtrl($logger){ - $logger.log('Service 1 - Hello Ctrl Init'); +function HelloCtrl ($logger) { + $logger.log('Service 1 - Hello Ctrl Init'); } // localhost:8000/service1/hello -HelloCtrl.prototype.world = function($done) -{ - $done( { source: "service1", hello: "world" } ); +HelloCtrl.prototype.world = function ($done) { + $done({ source: 'service1', hello: 'world' }); }; diff --git a/examples/api/multiservice-multifile/service1/service1.js b/examples/api/multiservice-multifile/service1/service1.js index 66cbff3..b3b6673 100644 --- a/examples/api/multiservice-multifile/service1/service1.js +++ b/examples/api/multiservice-multifile/service1/service1.js @@ -1,6 +1,6 @@ module.exports = Service1; -function Service1($logger){ - $logger.log('Service 1 - Init'); +function Service1 ($logger) { + $logger.log('Service 1 - Init'); } diff --git a/examples/api/multiservice-multifile/service1/service1.routes.js b/examples/api/multiservice-multifile/service1/service1.routes.js index 34bfcb5..25f6704 100644 --- a/examples/api/multiservice-multifile/service1/service1.routes.js +++ b/examples/api/multiservice-multifile/service1/service1.routes.js @@ -1,11 +1,11 @@ // Routes module.exports = [ - { - api: "/service1/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "world" // defined in controller module" - } + { + api: '/service1/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'world' // defined in controller module" } + } ]; diff --git a/examples/api/multiservice-multifile/service2/controllers/hello.js b/examples/api/multiservice-multifile/service2/controllers/hello.js index c2eea71..d5333b4 100644 --- a/examples/api/multiservice-multifile/service2/controllers/hello.js +++ b/examples/api/multiservice-multifile/service2/controllers/hello.js @@ -2,12 +2,11 @@ module.exports = HelloCtrl; -function HelloCtrl($logger){ - $logger.log('Service 2 - Hello Ctrl Init'); +function HelloCtrl ($logger) { + $logger.log('Service 2 - Hello Ctrl Init'); } // localhost:8000/service2/hello -HelloCtrl.prototype.world = function($done) -{ - $done( { source: "service2", hello: "world" } ); +HelloCtrl.prototype.world = function ($done) { + $done({ source: 'service2', hello: 'world' }); }; diff --git a/examples/api/multiservice-multifile/service2/service2.js b/examples/api/multiservice-multifile/service2/service2.js index 6ed2630..fbd88d0 100644 --- a/examples/api/multiservice-multifile/service2/service2.js +++ b/examples/api/multiservice-multifile/service2/service2.js @@ -1,6 +1,6 @@ module.exports = Service2; -function Service2($logger){ - $logger.log('Service 2 - Init'); +function Service2 ($logger) { + $logger.log('Service 2 - Init'); } diff --git a/examples/api/multiservice-multifile/service2/service2.routes.js b/examples/api/multiservice-multifile/service2/service2.routes.js index 72fdab5..b15d1bb 100644 --- a/examples/api/multiservice-multifile/service2/service2.routes.js +++ b/examples/api/multiservice-multifile/service2/service2.routes.js @@ -1,11 +1,11 @@ // Routes module.exports = [ - { - api: "/service2/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "world" // defined in controller module" - } + { + api: '/service2/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'world' // defined in controller module" } + } ]; diff --git a/examples/api/multiservice-singlefile/app.js b/examples/api/multiservice-singlefile/app.js index 16bfd98..323f6c4 100644 --- a/examples/api/multiservice-singlefile/app.js +++ b/examples/api/multiservice-singlefile/app.js @@ -4,38 +4,43 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // load config and routes var hyper = new Hyper(options); var app = hyper.start({ - services: { - "s1": { - routes: [{ - api: "/service1/hello", - method: { - get: function hello($done) - { - $done( { hello: "world", ts: new Date()} ); - } - } - }] - }, - "s2": { - routes: [{ - api: "/service2/hello", - method: { - get: function hello($done) - { - $done( { hello: "world", ts: new Date()} ); - } - } - }] + services: { + 's1': { + routes: [{ + api: '/service1/hello', + method: { + get: function hello ($done) { + $done({ + hello: 'world', + ts: new Date() + }); + } } + }] + }, + 's2': { + routes: [{ + api: '/service2/hello', + method: { + get: function hello ($done) { + $done({ + hello: 'world', + ts: new Date() + }); + } + } + }] } + } }); // !-- FOR TESTS diff --git a/examples/api/prepost-route-multifile/app.js b/examples/api/prepost-route-multifile/app.js index 5fc9694..3df08ad 100644 --- a/examples/api/prepost-route-multifile/app.js +++ b/examples/api/prepost-route-multifile/app.js @@ -4,17 +4,16 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! - // Load's config files then // Start web server var hyper = new Hyper(options); var app = hyper.start(); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/prepost-route-multifile/app.routes.js b/examples/api/prepost-route-multifile/app.routes.js index 01958a0..8b8b1a7 100644 --- a/examples/api/prepost-route-multifile/app.routes.js +++ b/examples/api/prepost-route-multifile/app.routes.js @@ -1,11 +1,11 @@ // Routes module.exports = [ - { - api: "/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "hello" // defined in controller module" - } + { + api: '/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'hello' // defined in controller module" } + } ]; diff --git a/examples/api/prepost-route-multifile/controllers/hello.js b/examples/api/prepost-route-multifile/controllers/hello.js index da63753..a2b12ed 100644 --- a/examples/api/prepost-route-multifile/controllers/hello.js +++ b/examples/api/prepost-route-multifile/controllers/hello.js @@ -2,58 +2,55 @@ module.exports = HelloCtrl; -function HelloCtrl(){ - this.data = { hello: "world" }; +function HelloCtrl () { + this.data = { hello: 'world' }; } // support all the same features as handles // (eg, generators, promises, throw errors...) -HelloCtrl.prototype.$preRoute = function($input, $error, $q){ - if(!$input.query || !$input.query.q) { +HelloCtrl.prototype.$preRoute = function ($input, $error, $q) { + if (!$input.query || !$input.query.q) { // TODO: support throwing errors - $error('missing search input', 404); + $error('missing search input', 404); /* throw new Error({ errorCode: 404, errorMsg: 'missing search input' }); */ - } else { + } + else { // can return promise, like handler - return $q.resolve({ - pre: $input.query.q, - data: this.data - }); - } -} + return $q.resolve({ + pre: $input.query.q, + data: this.data + }); + } +}; // not called if error thown -HelloCtrl.prototype.$postRoute = function($output) { - - if($output.code > 399) { - - var errorMsg = $output.data; - $output.data = { - errorMsg: errorMsg, - errorCode: $output.code - } - - } else { +HelloCtrl.prototype.$postRoute = function ($output) { + if ($output.code > 399) { + var errorMsg = $output.data; + $output.data = { + errorMsg: errorMsg, + errorCode: $output.code + }; + } + else { // can return data, like handler - $output.data.post = 'test2'; - } + $output.data.post = 'test2'; + } - return $output; -} + return $output; +}; // localhost:8000/hello -HelloCtrl.prototype.hello = function($done, $output) -{ - $output.data.hello = 'test hello'; - return $output; +HelloCtrl.prototype.hello = function ($done, $output) { + $output.data.hello = 'test hello'; + return $output; }; - /* //TODO make this same $routes example in ES6, decortators would be nice //make hyper controller class? diff --git a/examples/api/resolver-basic/app.js b/examples/api/resolver-basic/app.js index ba40bde..032ea62 100644 --- a/examples/api/resolver-basic/app.js +++ b/examples/api/resolver-basic/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // load config and routes diff --git a/examples/api/resolver-basic/app.routes.js b/examples/api/resolver-basic/app.routes.js index 14dab73..c1cb712 100644 --- a/examples/api/resolver-basic/app.routes.js +++ b/examples/api/resolver-basic/app.routes.js @@ -1,29 +1,29 @@ // Routes module.exports = [ - { - api: '/hello.new', - resolve: { - data: 'hello-data' - }, - controller: "hello", - method: { - get: 'hello' - } + { + api: '/hello.new', + resolve: { + data: 'hello-data' }, - { - redirect: { - from: '/hello', - to: '/hello.new' - } - }, - { - static: 'static' - }, - { - otherwise: { - redirect: { - to: '/' - } - } + controller: 'hello', + method: { + get: 'hello' + } + }, + { + redirect: { + from: '/hello', + to: '/hello.new' + } + }, + { + static: 'static' + }, + { + otherwise: { + redirect: { + to: '/' + } } + } ]; diff --git a/examples/api/resolver-basic/controllers/hello.js b/examples/api/resolver-basic/controllers/hello.js index 826d985..abe36aa 100644 --- a/examples/api/resolver-basic/controllers/hello.js +++ b/examples/api/resolver-basic/controllers/hello.js @@ -2,11 +2,10 @@ module.exports = HelloCtrl; -function HelloCtrl(){ +function HelloCtrl () { } // localhost:8000/hello -HelloCtrl.prototype.hello = function($done, data) -{ - $done( data ); +HelloCtrl.prototype.hello = function ($done, data) { + $done(data); }; diff --git a/examples/api/resolver-basic/resolvers/hello-data.js b/examples/api/resolver-basic/resolvers/hello-data.js index 6660fac..faab042 100644 --- a/examples/api/resolver-basic/resolvers/hello-data.js +++ b/examples/api/resolver-basic/resolvers/hello-data.js @@ -4,12 +4,11 @@ var when = require('when'); module.exports = HelloDataResolver; -function HelloDataResolver(){ +function HelloDataResolver () { } -HelloDataResolver.prototype.data = function() -{ - return when.promise(function(resolve) { - resolve( { hello: "world", ts: new Date() } ); - }); +HelloDataResolver.prototype.data = function () { + return when.promise(function (resolve) { + resolve({ hello: 'world', ts: new Date() }); + }); }; diff --git a/examples/api/resource-multifile/app.js b/examples/api/resource-multifile/app.js index 134b36b..cb0dbd9 100644 --- a/examples/api/resource-multifile/app.js +++ b/examples/api/resource-multifile/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // load config and routes diff --git a/examples/api/resource-multifile/service1/controllers/hello.js b/examples/api/resource-multifile/service1/controllers/hello.js index 2d8c995..ab14e48 100644 --- a/examples/api/resource-multifile/service1/controllers/hello.js +++ b/examples/api/resource-multifile/service1/controllers/hello.js @@ -2,12 +2,11 @@ module.exports = HelloCtrl; -function HelloCtrl($logger){ - $logger.log('Service 1 - Hello Ctrl Init'); +function HelloCtrl ($logger) { + $logger.log('Service 1 - Hello Ctrl Init'); } // localhost:8000/service1/hello -HelloCtrl.prototype.world = function($done, s1Hello ) -{ - $done( s1Hello.world() ); +HelloCtrl.prototype.world = function ($done, s1Hello) { + $done(s1Hello.world()); }; diff --git a/examples/api/resource-multifile/service1/service1.js b/examples/api/resource-multifile/service1/service1.js index c7b6776..6fa2610 100644 --- a/examples/api/resource-multifile/service1/service1.js +++ b/examples/api/resource-multifile/service1/service1.js @@ -1,8 +1,8 @@ module.exports = Service1; -function Service1($logger, $resource){ - $logger.log('Service 1 - Init'); +function Service1 ($logger, $resource) { + $logger.log('Service 1 - Init'); - $resource.add('s1Hello', require('./service1.resource.hello.js')); + $resource.add('s1Hello', require('./service1.resource.hello.js')); } diff --git a/examples/api/resource-multifile/service1/service1.resource.hello.js b/examples/api/resource-multifile/service1/service1.resource.hello.js index fdeb2e0..2eeced4 100644 --- a/examples/api/resource-multifile/service1/service1.resource.hello.js +++ b/examples/api/resource-multifile/service1/service1.resource.hello.js @@ -2,28 +2,28 @@ module.exports = resourceHello; -function resourceHello() { - this._data = {}; +function resourceHello () { + this._data = {}; } // AUTO run when resource is created by Hyper.io -resourceHello.prototype.$init = function($q, $logger) { - var deferer = $q.defer(); +resourceHello.prototype.$init = function ($q, $logger) { + var deferer = $q.defer(); - $logger.log('service1.resourceHello Init Running...'); - setTimeout(function() { - this._data = { - hello: "world service 1 resource", - ts: new Date() - }; + $logger.log('service1.resourceHello Init Running...'); + setTimeout(function () { + this._data = { + hello: 'world service 1 resource', + ts: new Date() + }; - $logger.log('service1.resourceHello Init Done.'); - deferer.resolve("service1"); - }.bind(this), 2 * 1000); + $logger.log('service1.resourceHello Init Done.'); + deferer.resolve('service1'); + }.bind(this), 2 * 1000); - return deferer.promise; + return deferer.promise; }; -resourceHello.prototype.world = function() { - return this._data; +resourceHello.prototype.world = function () { + return this._data; }; diff --git a/examples/api/resource-multifile/service1/service1.routes.js b/examples/api/resource-multifile/service1/service1.routes.js index 34bfcb5..25f6704 100644 --- a/examples/api/resource-multifile/service1/service1.routes.js +++ b/examples/api/resource-multifile/service1/service1.routes.js @@ -1,11 +1,11 @@ // Routes module.exports = [ - { - api: "/service1/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "world" // defined in controller module" - } + { + api: '/service1/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'world' // defined in controller module" } + } ]; diff --git a/examples/api/resource-multifile/service2/controllers/hello.js b/examples/api/resource-multifile/service2/controllers/hello.js index 8065c6c..8b7bd46 100644 --- a/examples/api/resource-multifile/service2/controllers/hello.js +++ b/examples/api/resource-multifile/service2/controllers/hello.js @@ -2,12 +2,11 @@ module.exports = HelloCtrl; -function HelloCtrl($logger){ - $logger.log('Service 2 - Hello Ctrl Init'); +function HelloCtrl ($logger) { + $logger.log('Service 2 - Hello Ctrl Init'); } // localhost:8000/service2/hello -HelloCtrl.prototype.world = function($done, s2Hello) -{ - $done( s2Hello.world() ); +HelloCtrl.prototype.world = function ($done, s2Hello) { + $done(s2Hello.world()); }; diff --git a/examples/api/resource-multifile/service2/service2.js b/examples/api/resource-multifile/service2/service2.js index c735add..0d7916e 100644 --- a/examples/api/resource-multifile/service2/service2.js +++ b/examples/api/resource-multifile/service2/service2.js @@ -1,8 +1,8 @@ module.exports = Service2; -function Service2($logger, $resource){ - $logger.log('Service 2 - Init'); +function Service2 ($logger, $resource) { + $logger.log('Service 2 - Init'); - $resource.add('s2Hello', require('./service2.resource.hello.js') ); + $resource.add('s2Hello', require('./service2.resource.hello.js')); } diff --git a/examples/api/resource-multifile/service2/service2.resource.hello.js b/examples/api/resource-multifile/service2/service2.resource.hello.js index fd6089e..8a0f84e 100644 --- a/examples/api/resource-multifile/service2/service2.resource.hello.js +++ b/examples/api/resource-multifile/service2/service2.resource.hello.js @@ -2,25 +2,25 @@ module.exports = resourceHello; -function resourceHello() { +function resourceHello () { this._data = { - hello: "world service 2 resource" + hello: 'world service 2 resource' }; } // AUTO run after the server has start, use for all Service to Service Init Com -resourceHello.prototype.$postStartInit = function($q, $services, $logger) { +resourceHello.prototype.$postStartInit = function ($q, $services, $logger) { $logger.log('service2.resourceHello Post Start Init Running...'); // get "ts" data from service1 return $services.find('service1') .get('/service1/hello') - .then(function(data){ + .then(function (data) { $logger.log('service1.resourceHello Post Start Init Done.'); this._data.ts = data.ts; }.bind(this)); }; -resourceHello.prototype.world = function() { - return this._data; +resourceHello.prototype.world = function () { + return this._data; }; diff --git a/examples/api/resource-multifile/service2/service2.routes.js b/examples/api/resource-multifile/service2/service2.routes.js index 72fdab5..b15d1bb 100644 --- a/examples/api/resource-multifile/service2/service2.routes.js +++ b/examples/api/resource-multifile/service2/service2.routes.js @@ -1,11 +1,11 @@ // Routes module.exports = [ - { - api: "/service2/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "world" // defined in controller module" - } + { + api: '/service2/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'world' // defined in controller module" } + } ]; diff --git a/examples/api/resource-singlefile/app.js b/examples/api/resource-singlefile/app.js index ade06d2..27eeeac 100644 --- a/examples/api/resource-singlefile/app.js +++ b/examples/api/resource-singlefile/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // load config and routes @@ -13,15 +14,14 @@ var hyper = new Hyper(options); // setup routes hyper.load({ - routes: [{ - api: "/hello", - method: { - get: function world($done, hello) - { - $done( hello.world() ); - } - } - }] + routes: [{ + api: '/hello', + method: { + get: function world ($done, hello) { + $done(hello.world()); + } + } + }] }); hyper.resource('hello', require('./resource.hello.js')); diff --git a/examples/api/resource-singlefile/resource.hello.js b/examples/api/resource-singlefile/resource.hello.js index 2b0fd6f..ca703fe 100644 --- a/examples/api/resource-singlefile/resource.hello.js +++ b/examples/api/resource-singlefile/resource.hello.js @@ -2,12 +2,12 @@ module.exports = resourceHello; -function resourceHello() { +function resourceHello () { } -resourceHello.prototype.world = function() { - return { - hello: "world resource", - ts: new Date() - }; +resourceHello.prototype.world = function () { + return { + hello: 'world resource', + ts: new Date() + }; }; diff --git a/examples/api/resource-sqlite/app.js b/examples/api/resource-sqlite/app.js index d69fff7..ba14217 100644 --- a/examples/api/resource-sqlite/app.js +++ b/examples/api/resource-sqlite/app.js @@ -4,26 +4,26 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // load config and routes var hyper = new Hyper(options); hyper.load({ - routes: [{ - api: "/hello", - method: { - get: function world($done, hello) - { - hello.world() - .then(function(data){ - $done(data); - }); - } - } - }] + routes: [{ + api: '/hello', + method: { + get: function world ($done, hello) { + hello.world() + .then(function (data) { + $done(data); + }); + } + } + }] }); hyper.resource('hello', require('./resource.hello.js')); diff --git a/examples/api/resource-sqlite/resource.hello.js b/examples/api/resource-sqlite/resource.hello.js index fbf2c94..1659da4 100644 --- a/examples/api/resource-sqlite/resource.hello.js +++ b/examples/api/resource-sqlite/resource.hello.js @@ -4,33 +4,38 @@ var sqlite3 = require('sqlite3').verbose(); module.exports = resourceHello; -function resourceHello($q) { - this.$q = $q; - this.db = new sqlite3.Database(':memory:'); +function resourceHello ($q, $logger) { + this.$q = $q; + this._L = $logger; + this.db = new sqlite3.Database(':memory:'); } -resourceHello.prototype.world = function() { - var deferred = this.$q.defer(); +resourceHello.prototype.world = function () { + var deferred = this.$q.defer(); - this.db.serialize(function() { - this.db.run("CREATE TABLE IF NOT EXISTS test (info TEXT)"); + this.db.serialize(function () { + this.db.run('CREATE TABLE IF NOT EXISTS test (info TEXT)'); - var stmt = this.db.prepare("INSERT INTO test VALUES (?)"); - stmt.run("td:"+(new Date())); - stmt.finalize(); + var stmt = this.db.prepare('INSERT INTO test VALUES (?)'); + stmt.run('td:' + (new Date())); + stmt.finalize(); - this.db.all("SELECT rowid AS id, info FROM test", function(err, rows) { - var outRow = []; - rows.forEach(function (row) { - outRow.push(row.id + ":" + row.info); - }); + this.db.all('SELECT rowid AS id, info FROM test', function (err, rows) { + if (err) { + this._L.error('DB Error:', err); + } - deferred.resolve({ - hello: "world", - ts: outRow.join(', ') - }); - }.bind(this)); - }.bind(this)); + var outRow = []; + rows.forEach(function (row) { + outRow.push(row.id + ':' + row.info); + }); - return deferred.promise; + deferred.resolve({ + hello: 'world', + ts: outRow.join(', ') + }); + }); + }.bind(this)); + + return deferred.promise; }; diff --git a/examples/api/session-basic/app.js b/examples/api/session-basic/app.js index 020484d..64d7438 100644 --- a/examples/api/session-basic/app.js +++ b/examples/api/session-basic/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes @@ -14,40 +15,37 @@ var hyper = new Hyper(options); var app = hyper .start({ - routes: [ - { + routes: [ + { // http://localhost:8000/login?username=joe - api: "/login", - method: { - get: function login($done, $session, $input) - { - $session.username = $input.query.username; - $done( { - hello: $session.username - } ); - } - } - }, - { + api: '/login', + method: { + get: function login ($done, $session, $input) { + $session.username = $input.query.username; + $done({ + hello: $session.username + }); + } + } + }, + { // http://localhost:8000/hello - api: "/hello", - method: { - get: function world($done, $session) - { - $done( { - hello: "world", - session: $session - } ); - } - } + api: '/hello', + method: { + get: function world ($done, $session) { + $done({ + hello: 'world', + session: $session + }); } - ] - }).then(function(server){ - server.logger().log("Server Started"); - return server; + } + } + ] + }).then(function (server) { + server.logger().log('Server Started'); + return server; }); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/api/session-custom/app.js b/examples/api/session-custom/app.js index f6466ca..1bc5e88 100644 --- a/examples/api/session-custom/app.js +++ b/examples/api/session-custom/app.js @@ -5,61 +5,59 @@ var session = require('express-session'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes options.session = { - secret: "keyboard kat", - resave: false, // depends on the session store, see https://github.com/expressjs/session#resave - saveUninitialized: false, // depends on several cases, see https://github.com/expressjs/session#saveuninitialized - cookie: { - //secure: true, // enable only if https - path: '/', - httpOnly : true, - maxAge: 1000 * 60 * 24 // 24 hours - }, - storeInst: new session.MemoryStore() + secret: 'keyboard kat', + resave: false, // depends on the session store, see https://github.com/expressjs/session#resave + saveUninitialized: false, // depends on several cases, see https://github.com/expressjs/session#saveuninitialized + cookie: { + // secure: true, // enable only if https + path: '/', + httpOnly: true, + maxAge: 1000 * 60 * 24 // 24 hours + }, + storeInst: new session.MemoryStore() }; var hyper = new Hyper(options); var app = hyper .start({ - routes: [ - { + routes: [ + { // http://localhost:8000/login?username=joe - api: "/login", - method: { - get: function login($done, $session, $input) - { - $session.username = $input.query.username; - $done( { - hello: $session.username - } ); - } - } - }, - { + api: '/login', + method: { + get: function login ($done, $session, $input) { + $session.username = $input.query.username; + $done({ + hello: $session.username + }); + } + } + }, + { // http://localhost:8000/hello - api: "/hello", - method: { - get: function world($done, $session) - { - $done( { - hello: "world", - session: $session - } ); - } - } + api: '/hello', + method: { + get: function world ($done, $session) { + $done({ + hello: 'world', + session: $session + }); } - ] - }).then(function(server){ - server.logger().log("Server Started"); - return server; + } + } + ] + }).then(function (server) { + server.logger().log('Server Started'); + return server; }); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/config/helloworld-multifile/controllers/hello.js b/examples/config/helloworld-multifile/controllers/hello.js index 9fce101..a170cbc 100644 --- a/examples/config/helloworld-multifile/controllers/hello.js +++ b/examples/config/helloworld-multifile/controllers/hello.js @@ -2,13 +2,12 @@ module.exports = HelloCtrl; -function HelloCtrl($logger, $config){ - $logger.log('Hello Ctrl - config:', $config); +function HelloCtrl ($logger, $config) { + $logger.log('Hello Ctrl - config:', $config); } // localhost:8000/hello -HelloCtrl.prototype.world = function($done, $logger, $config) -{ - $logger.log('Hello World Handler - config:', $config); - $done( $config ); +HelloCtrl.prototype.world = function ($done, $logger, $config) { + $logger.log('Hello World Handler - config:', $config); + $done($config); }; diff --git a/examples/config/helloworld-multifile/myserver.js b/examples/config/helloworld-multifile/myserver.js index 8b36178..c220cd2 100644 --- a/examples/config/helloworld-multifile/myserver.js +++ b/examples/config/helloworld-multifile/myserver.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes diff --git a/examples/config/helloworld-multifile/myserver.routes.js b/examples/config/helloworld-multifile/myserver.routes.js index e0d9d25..24e83c0 100644 --- a/examples/config/helloworld-multifile/myserver.routes.js +++ b/examples/config/helloworld-multifile/myserver.routes.js @@ -1,11 +1,11 @@ // Routes module.exports = [ - { - api: "/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "world" // defined in controller module" - } + { + api: '/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'world' // defined in controller module" } + } ]; diff --git a/examples/config/helloworld-singlefile/app.js b/examples/config/helloworld-singlefile/app.js index d2049c2..a64d110 100644 --- a/examples/config/helloworld-singlefile/app.js +++ b/examples/config/helloworld-singlefile/app.js @@ -4,27 +4,27 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = null; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes -var hyper = new Hyper(options || { port: 8002 } ); +var hyper = new Hyper(options || { port: 8002 }); // load config and routes var app = hyper.start({ - routes: [ - { - api: "/hello", - method: { - get: function world($done, $config, $logger) - { - $logger.log('hello world config:', $config); - $done( $config ); - } - } + routes: [ + { + api: '/hello', + method: { + get: function world ($done, $config, $logger) { + $logger.log('hello world config:', $config); + $done($config); } - ] + } + } + ] }); // !-- FOR TESTS diff --git a/examples/config/multiservice-singlefile/server.config.js b/examples/config/multiservice-singlefile/server.config.js index fe8648a..e4d71b7 100644 --- a/examples/config/multiservice-singlefile/server.config.js +++ b/examples/config/multiservice-singlefile/server.config.js @@ -1,8 +1,8 @@ module.exports = { - "service1": { - "from": "Service 1" - }, - "service2": { - "from": "Service 2" - } + 'service1': { + 'from': 'Service 1' + }, + 'service2': { + 'from': 'Service 2' + } }; diff --git a/examples/config/multiservice-singlefile/server.js b/examples/config/multiservice-singlefile/server.js index 71835d3..47a71df 100644 --- a/examples/config/multiservice-singlefile/server.js +++ b/examples/config/multiservice-singlefile/server.js @@ -4,38 +4,37 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes var hyper = new Hyper(options); var app = hyper.start({ - services: { - "service1": { - routes: [{ - api: "/service1/hello", - method: { - get: function hello($done, $config) - { - $done( { "source":"service1", "ts": new Date(), config: $config } ); - } - } - }] - }, - "service2": { - routes: [{ - api: "/service2/hello", - method: { - get: function hello($done, $config) - { - $done( { "source":"service2", "ts": new Date(), config: $config } ); - } - } - }] + services: { + 'service1': { + routes: [{ + api: '/service1/hello', + method: { + get: function hello ($done, $config) { + $done({ 'source': 'service1', 'ts': new Date(), config: $config }); + } } + }] + }, + 'service2': { + routes: [{ + api: '/service2/hello', + method: { + get: function hello ($done, $config) { + $done({ 'source': 'service2', 'ts': new Date(), config: $config }); + } + } + }] } + } }); // !-- FOR TESTS diff --git a/examples/config/shared/app.js b/examples/config/shared/app.js index fb67126..960f647 100644 --- a/examples/config/shared/app.js +++ b/examples/config/shared/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = null; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes @@ -13,18 +14,17 @@ var hyper = new Hyper(options); // load config and routes var app = hyper.start({ - routes: [ - { - api: "/hello", - method: { - get: function world($done, $sharedConfig, $logger) - { - $logger.log('hello world config:', $sharedConfig); - $done( $sharedConfig ); - } - } + routes: [ + { + api: '/hello', + method: { + get: function world ($done, $sharedConfig, $logger) { + $logger.log('hello world config:', $sharedConfig); + $done($sharedConfig); } - ] + } + } + ] }); // !-- FOR TESTS diff --git a/examples/custom-response/helloworld-singlefile/app.js b/examples/custom-response/helloworld-singlefile/app.js index 40f3925..fa40695 100755 --- a/examples/custom-response/helloworld-singlefile/app.js +++ b/examples/custom-response/helloworld-singlefile/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes @@ -13,21 +14,20 @@ var hyper = new Hyper(options); // load routes var app = hyper.start({ - routes: [ - { - api: "/hello", - method: { - get: function world($custom) - { - var data = 'iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAAB+FBMVEUAAAA/mUPidDHiLi5Cn0XkNTPmeUrkdUg/m0Q0pEfcpSbwaVdKskg+lUP4zA/iLi3msSHkOjVAmETdJSjtYFE/lkPnRj3sWUs8kkLeqCVIq0fxvhXqUkbVmSjwa1n1yBLepyX1xxP0xRXqUkboST9KukpHpUbuvRrzrhF/ljbwaljuZFM4jELaoSdLtElJrUj1xxP6zwzfqSU4i0HYnydMtUlIqUfywxb60AxZqEXaoifgMCXptR9MtklHpEY2iUHWnSjvvRr70QujkC+pUC/90glMuEnlOjVMt0j70QriLS1LtEnnRj3qUUXfIidOjsxAhcZFo0bjNDH0xxNLr0dIrUdmntVTkMoyfL8jcLBRuErhJyrgKyb4zA/5zg3tYFBBmUTmQTnhMinruBzvvhnxwxZ/st+Ktt5zp9hqota2vtK6y9FemNBblc9HiMiTtMbFtsM6gcPV2r6dwroseLrMrbQrdLGdyKoobKbo3Zh+ynrgVllZulTsXE3rV0pIqUf42UVUo0JyjEHoS0HmsiHRGR/lmRz/1hjqnxjvpRWfwtOhusaz0LRGf7FEfbDVmqHXlJeW0pbXq5bec3fX0nTnzmuJuWvhoFFhm0FtrziBsjaAaDCYWC+uSi6jQS3FsSfLJiTirCOkuCG1KiG+wSC+GBvgyhTszQ64Z77KAAAARXRSTlMAIQRDLyUgCwsE6ebm5ubg2dLR0byXl4FDQzU1NDEuLSUgC+vr6urq6ubb29vb2tra2tG8vLu7u7uXl5eXgYGBgYGBLiUALabIAAABsElEQVQoz12S9VPjQBxHt8VaOA6HE+AOzv1wd7pJk5I2adpCC7RUcHd3d3fXf5PvLkxheD++z+yb7GSRlwD/+Hj/APQCZWxM5M+goF+RMbHK594v+tPoiN1uHxkt+xzt9+R9wnRTZZQpXQ0T5uP1IQxToyOAZiQu5HEpjeA4SWIoksRxNiGC1tRZJ4LNxgHgnU5nJZBDvuDdl8lzQRBsQ+s9PZt7s7Pz8wsL39/DkIfZ4xlB2Gqsq62ta9oxVlVrNZpihFRpGO9fzQw1ms0NDWZz07iGkJmIFH8xxkc3a/WWlubmFkv9AB2SEpDvKxbjidN2faseaNV3zoHXvv7wMODJdkOHAegweAfFPx4G67KluxzottCU9n8CUqXzcIQdXOytAHqXxomvykhEKN9EFutG22p//0rbNvHVxiJywa8yS2KDfV1dfbu31H8jF1RHiTKtWYeHxUvq3bn0pyjCRaiRU6aDO+gb3aEfEeVNsDgm8zzLy9egPa7Qt8TSJdwhjplk06HH43ZNJ3s91KKCHQ5x4sw1fRGYDZ0n1L4FKb9/BP5JLYxToheoFCVxz57PPS8UhhEpLBVeAAAAAElFTkSuQmCC'; - $custom({ - data: new Buffer(data, 'base64'), - filename: "test.png" - }); - } - } + routes: [ + { + api: '/hello', + method: { + get: function world ($custom) { + var data = 'iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAAB+FBMVEUAAAA/mUPidDHiLi5Cn0XkNTPmeUrkdUg/m0Q0pEfcpSbwaVdKskg+lUP4zA/iLi3msSHkOjVAmETdJSjtYFE/lkPnRj3sWUs8kkLeqCVIq0fxvhXqUkbVmSjwa1n1yBLepyX1xxP0xRXqUkboST9KukpHpUbuvRrzrhF/ljbwaljuZFM4jELaoSdLtElJrUj1xxP6zwzfqSU4i0HYnydMtUlIqUfywxb60AxZqEXaoifgMCXptR9MtklHpEY2iUHWnSjvvRr70QujkC+pUC/90glMuEnlOjVMt0j70QriLS1LtEnnRj3qUUXfIidOjsxAhcZFo0bjNDH0xxNLr0dIrUdmntVTkMoyfL8jcLBRuErhJyrgKyb4zA/5zg3tYFBBmUTmQTnhMinruBzvvhnxwxZ/st+Ktt5zp9hqota2vtK6y9FemNBblc9HiMiTtMbFtsM6gcPV2r6dwroseLrMrbQrdLGdyKoobKbo3Zh+ynrgVllZulTsXE3rV0pIqUf42UVUo0JyjEHoS0HmsiHRGR/lmRz/1hjqnxjvpRWfwtOhusaz0LRGf7FEfbDVmqHXlJeW0pbXq5bec3fX0nTnzmuJuWvhoFFhm0FtrziBsjaAaDCYWC+uSi6jQS3FsSfLJiTirCOkuCG1KiG+wSC+GBvgyhTszQ64Z77KAAAARXRSTlMAIQRDLyUgCwsE6ebm5ubg2dLR0byXl4FDQzU1NDEuLSUgC+vr6urq6ubb29vb2tra2tG8vLu7u7uXl5eXgYGBgYGBLiUALabIAAABsElEQVQoz12S9VPjQBxHt8VaOA6HE+AOzv1wd7pJk5I2adpCC7RUcHd3d3fXf5PvLkxheD++z+yb7GSRlwD/+Hj/APQCZWxM5M+goF+RMbHK594v+tPoiN1uHxkt+xzt9+R9wnRTZZQpXQ0T5uP1IQxToyOAZiQu5HEpjeA4SWIoksRxNiGC1tRZJ4LNxgHgnU5nJZBDvuDdl8lzQRBsQ+s9PZt7s7Pz8wsL39/DkIfZ4xlB2Gqsq62ta9oxVlVrNZpihFRpGO9fzQw1ms0NDWZz07iGkJmIFH8xxkc3a/WWlubmFkv9AB2SEpDvKxbjidN2faseaNV3zoHXvv7wMODJdkOHAegweAfFPx4G67KluxzottCU9n8CUqXzcIQdXOytAHqXxomvykhEKN9EFutG22p//0rbNvHVxiJywa8yS2KDfV1dfbu31H8jF1RHiTKtWYeHxUvq3bn0pyjCRaiRU6aDO+gb3aEfEeVNsDgm8zzLy9egPa7Qt8TSJdwhjplk06HH43ZNJ3s91KKCHQ5x4sw1fRGYDZ0n1L4FKb9/BP5JLYxToheoFCVxz57PPS8UhhEpLBVeAAAAAElFTkSuQmCC'; + $custom({ + data: new Buffer(data, 'base64'), + filename: 'test.png' + }); } - ] + } + } + ] }); // !-- FOR TESTS diff --git a/examples/export/helloworld-multifile/app.js b/examples/export/helloworld-multifile/app.js index 8247549..253e3de 100644 --- a/examples/export/helloworld-multifile/app.js +++ b/examples/export/helloworld-multifile/app.js @@ -4,11 +4,11 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! - // Load's config files then // Start web server var hyper = new Hyper(options); @@ -16,7 +16,6 @@ var app = hyper.start( require('./external-service') ); - // !-- FOR TESTS module.exports = app; // --! diff --git a/examples/export/helloworld-multifile/external-service/controllers/hello.js b/examples/export/helloworld-multifile/external-service/controllers/hello.js index 063d877..8604525 100644 --- a/examples/export/helloworld-multifile/external-service/controllers/hello.js +++ b/examples/export/helloworld-multifile/external-service/controllers/hello.js @@ -2,24 +2,21 @@ module.exports = HelloCtrl; -function HelloCtrl(){ - this.data = { hello: "world" }; +function HelloCtrl () { + this.data = { hello: 'world' }; } // localhost:8000/hello -HelloCtrl.prototype.hello = function($done, $config) -{ - $done( $config ); +HelloCtrl.prototype.hello = function ($done, $config) { + $done($config); }; // localhost:8000/world -HelloCtrl.prototype.world = function() -{ - return this.data; +HelloCtrl.prototype.world = function () { + return this.data; }; // localhost:8000/test -HelloCtrl.prototype.test = function(util) -{ - return util.test(); +HelloCtrl.prototype.test = function (main) { + return main.test(); }; diff --git a/examples/export/helloworld-multifile/external-service/myservice.config.js b/examples/export/helloworld-multifile/external-service/myservice.config.js index 8aea7f2..1497cd3 100644 --- a/examples/export/helloworld-multifile/external-service/myservice.config.js +++ b/examples/export/helloworld-multifile/external-service/myservice.config.js @@ -1,3 +1,3 @@ module.exports = { - "hello": "world" + 'hello': 'world' }; diff --git a/examples/export/helloworld-multifile/external-service/myservice.js b/examples/export/helloworld-multifile/external-service/myservice.js index 4b49020..709bdd0 100644 --- a/examples/export/helloworld-multifile/external-service/myservice.js +++ b/examples/export/helloworld-multifile/external-service/myservice.js @@ -1,10 +1,10 @@ module.exports = Service; -function Service($logger){ - $logger.log('Service - Constructor'); +function Service ($logger) { + $logger.log('Service - Constructor'); } Service.prototype.$init = function ($logger) { - $logger.log('Service - Init'); + $logger.log('Service - Init'); }; diff --git a/examples/export/helloworld-multifile/external-service/myservice.resources.js b/examples/export/helloworld-multifile/external-service/myservice.resources.js index c1abfb5..c0e2b2b 100644 --- a/examples/export/helloworld-multifile/external-service/myservice.resources.js +++ b/examples/export/helloworld-multifile/external-service/myservice.resources.js @@ -1,4 +1,9 @@ -module.exports = { - 'util': require('./util') -}; +module.exports = [ + { + group: 'util', + name: 'main', + type: 'factory', + module: require('./util/main.js') + } +]; diff --git a/examples/export/helloworld-multifile/external-service/myservice.routes.js b/examples/export/helloworld-multifile/external-service/myservice.routes.js index 830f934..d702b10 100644 --- a/examples/export/helloworld-multifile/external-service/myservice.routes.js +++ b/examples/export/helloworld-multifile/external-service/myservice.routes.js @@ -1,25 +1,25 @@ // Routes module.exports = [ - { - api: "/hello", - controller: "hello", // default "/controllers/.js" - method: { - get: "hello" // defined in controller module" - } - }, - { - api: "/world", - controller: "hello", // default "/controllers/.js" - method: { - get: "world" // defined in controller module" - } - }, - { - api: "/test", - controller: "hello", // default "/controllers/.js" - method: { - get: "test" // defined in controller module" - } + { + api: '/hello', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'hello' // defined in controller module" } + }, + { + api: '/world', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'world' // defined in controller module" + } + }, + { + api: '/test', + controller: 'hello', // default "/controllers/.js" + method: { + get: 'test' // defined in controller module" + } + } ]; diff --git a/examples/export/helloworld-multifile/external-service/util/index.js b/examples/export/helloworld-multifile/external-service/util/index.js deleted file mode 100644 index 9d4d6a7..0000000 --- a/examples/export/helloworld-multifile/external-service/util/index.js +++ /dev/null @@ -1,9 +0,0 @@ - -function Util(){ -} - -Util.prototype.test = function(){ - return { 'test': 123 }; -}; - -module.exports = Util; \ No newline at end of file diff --git a/examples/export/helloworld-multifile/external-service/util/main.js b/examples/export/helloworld-multifile/external-service/util/main.js new file mode 100644 index 0000000..354d685 --- /dev/null +++ b/examples/export/helloworld-multifile/external-service/util/main.js @@ -0,0 +1,9 @@ + +function Util () { +} + +Util.prototype.test = function () { + return { 'test': 123 }; +}; + +module.exports = Util; diff --git a/examples/static/helloworld-basic/app.js b/examples/static/helloworld-basic/app.js index f55eb28..668737b 100644 --- a/examples/static/helloworld-basic/app.js +++ b/examples/static/helloworld-basic/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes @@ -13,14 +14,14 @@ var hyper = new Hyper(options); var app = hyper .start({ - routes: [ - { - static: "staticDir" - } - ] - }).then(function(server){ - server.logger().log("Server Started"); - return server; + routes: [ + { + static: 'staticDir' + } + ] + }).then(function (server) { + server.logger().log('Server Started'); + return server; }); // !-- FOR TESTS diff --git a/examples/static/helloworld-fromto/app.js b/examples/static/helloworld-fromto/app.js index ab0497d..94a5bdc 100644 --- a/examples/static/helloworld-fromto/app.js +++ b/examples/static/helloworld-fromto/app.js @@ -4,49 +4,49 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes var hyper = new Hyper(options); - var staticRoute1 = [ - "app/main", - { - from: "app/css/main1.css", - to: "main.css" - } + 'app/main', + { + from: 'app/css/main1.css', + to: 'main.css' + } ]; var staticRoute2 = { - root: "app", - list: [ - { - from: "main", - to: "/hello" - }, - { - from: "css/main2.css", - to: "/hello/main.css" - } - ] + root: 'app', + list: [ + { + from: 'main', + to: '/hello' + }, + { + from: 'css/main2.css', + to: '/hello/main.css' + } + ] }; var app = hyper .start({ - routes: [ - { - static: staticRoute1 - }, - { - static: staticRoute2 - } - ] - }).then(function(server){ - server.logger().log("Server Started"); - return server; + routes: [ + { + static: staticRoute1 + }, + { + static: staticRoute2 + } + ] + }).then(function (server) { + server.logger().log('Server Started'); + return server; }); // !-- FOR TESTS diff --git a/examples/static/helloworld-multisite/app.js b/examples/static/helloworld-multisite/app.js index 07f3408..bb0096e 100644 --- a/examples/static/helloworld-multisite/app.js +++ b/examples/static/helloworld-multisite/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes @@ -13,23 +14,23 @@ var hyper = new Hyper(options); var app = hyper .start({ - routes: [ + routes: [ + { + static: [ { - static: [ - { - from: "site1", - to: "/hello" - }, - { - from: "site2", - to: "/world" - } - ] + from: 'site1', + to: '/hello' + }, + { + from: 'site2', + to: '/world' } - ] - }).then(function(server){ - server.logger().log("Server Started"); - return server; + ] + } + ] + }).then(function (server) { + server.logger().log('Server Started'); + return server; }); // !-- FOR TESTS diff --git a/examples/static/helloworld-otherwise/app.js b/examples/static/helloworld-otherwise/app.js index 58753de..97305c8 100644 --- a/examples/static/helloworld-otherwise/app.js +++ b/examples/static/helloworld-otherwise/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes @@ -13,19 +14,19 @@ var hyper = new Hyper(options); var app = hyper .start({ - routes: [ - { - static: ["staticDir1", "staticDir2"] - }, - { - otherwise: { - static: "otherwiseDir" - } - } - ] - }).then(function(server){ - server.logger().log("Server Started"); - return server; + routes: [ + { + static: ['staticDir1', 'staticDir2'] + }, + { + otherwise: { + static: 'otherwiseDir' + } + } + ] + }).then(function (server) { + server.logger().log('Server Started'); + return server; }); // !-- FOR TESTS diff --git a/examples/template/helloworld-multifile/app.js b/examples/template/helloworld-multifile/app.js index 6f6d7a7..2103330 100755 --- a/examples/template/helloworld-multifile/app.js +++ b/examples/template/helloworld-multifile/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes diff --git a/examples/template/helloworld-multifile/app.routes.js b/examples/template/helloworld-multifile/app.routes.js index 6b491d8..096c863 100644 --- a/examples/template/helloworld-multifile/app.routes.js +++ b/examples/template/helloworld-multifile/app.routes.js @@ -1,15 +1,15 @@ // Routes module.exports = [ - { - view: "/hello", - template: { - //type: "ejs", // ejs will be detected based on file extension - file: "hello.ejs" - }, - controller: "hello", // default "/controllers/.js" - method: { - get: "world" // defined in controller module" - } + { + view: '/hello', + template: { + // type: "ejs", // ejs will be detected based on file extension + file: 'hello.ejs' + }, + controller: 'hello', // default "/controllers/.js" + method: { + get: 'world' // defined in controller module" } + } ]; diff --git a/examples/template/helloworld-multifile/controllers/hello.js b/examples/template/helloworld-multifile/controllers/hello.js index 2e67716..c35bbc1 100755 --- a/examples/template/helloworld-multifile/controllers/hello.js +++ b/examples/template/helloworld-multifile/controllers/hello.js @@ -2,14 +2,13 @@ module.exports = HelloCtrl; -function HelloCtrl(){ +function HelloCtrl () { } // localhost:8000/hello -HelloCtrl.prototype.world = function($done) -{ - $done( { - hello: "world", - ts: Date.now() - } ); +HelloCtrl.prototype.world = function ($done) { + $done({ + hello: 'world', + ts: Date.now() + }); }; diff --git a/examples/template/helloworld-singlefile/app.js b/examples/template/helloworld-singlefile/app.js index 8fc18e9..bf2cef7 100755 --- a/examples/template/helloworld-singlefile/app.js +++ b/examples/template/helloworld-singlefile/app.js @@ -4,8 +4,9 @@ var Hyper = require('../../../index.js'); // !-- FOR TESTS var options = {}; try { - options = JSON.parse(process.env.HYPER_OPTIONS); -} catch(err){} + options = JSON.parse(process.env.HYPER_OPTIONS); +} +catch (err) {} // --! // Load config and routes @@ -13,21 +14,20 @@ var hyper = new Hyper(options); // load routes var app = hyper.start({ - routes: [ - { - view: "/hello", - template: "hello <%= hello %> - <%= ts %>", - method: { - get: function world($done) - { - $done( { - hello: "world", - ts: Date.now() - } ); - } - } + routes: [ + { + view: '/hello', + template: 'hello <%= hello %> - <%= ts %>', + method: { + get: function world ($done) { + $done({ + hello: 'world', + ts: Date.now() + }); } - ] + } + } + ] }); // !-- FOR TESTS diff --git a/jsconfig.json b/jsconfig.json new file mode 100644 index 0000000..26af538 --- /dev/null +++ b/jsconfig.json @@ -0,0 +1,15 @@ +{ + // See https://go.microsoft.com/fwlink/?LinkId=759670 + // for the documentation about the jsconfig.json format + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "allowSyntheticDefaultImports": true + }, + "exclude": [ + "node_modules", + "jspm_packages", + "tmp", + "temp" + ] +} diff --git a/legacy/config.js b/legacy/config.js index fdda8f3..a57d141 100644 --- a/legacy/config.js +++ b/legacy/config.js @@ -1,12 +1,12 @@ 'use strict'; module.exports = { - env: "dev", - hyper: { - logger: { // logz options - name: 'HyperServiceManager' - }, - displayDebuggerInfo: false, - httpFramework: 'express' - } + env: 'dev', + hyper: { + logger: { // logz options + name: 'HyperServiceManager' + }, + displayDebuggerInfo: false, + httpFramework: 'express' // TODO: make this an object + } }; \ No newline at end of file diff --git a/legacy/handler.resource.js b/legacy/handler.resource.js index 3d8d8af..d463575 100644 --- a/legacy/handler.resource.js +++ b/legacy/handler.resource.js @@ -20,4 +20,10 @@ function ResourceHandler(ServiceManager, service) { * --------------------------------------------------- */ ResourceHandler.prototype.add = function (name, resourceModule, type) { return this._ServiceManager.addResource(name, resourceModule, type, this._service); -}; \ No newline at end of file +}; + +// ResourceHandler.prototype.getAllModules = function(name, resourceModule, type) { +// TODO: do I neede this? +// }; + +ResourceHandler.prototype.createInstance = function (group, name, resourceModule, type) {}; \ No newline at end of file diff --git a/legacy/http.framework.express.js b/legacy/http.framework.express.js index 7633e6a..b87a873 100755 --- a/legacy/http.framework.express.js +++ b/legacy/http.framework.express.js @@ -23,302 +23,297 @@ var mime = require('mime'); var Util = require('./util.js'); var logger = null; -module.exports = HttpFramework_Express; +module.exports = HttpFrameworkExpress; // TODO: add https support -function HttpFramework_Express(options, $stats) { - this._options = _.merge({ - env: 'dev', - port: 8000, - compress: true, - urlencoded: true, - parser: { - cookies: true, - json: true - }, - session: false - }, options); - - if (process.env.PORT) { - this._options.port = process.env.PORT; - } - - this._stats = $stats; - - logger = Util.logger('Express'); - - this._app = express(); - this._server = null; +function HttpFrameworkExpress(options, $stats) { + this._options = _.merge({ + env: 'dev', + port: 8000, + compress: true, + urlencoded: true, + parser: { + cookies: true, + json: true + }, + session: false + }, options); + + if (process.env.PORT) { + this._options.port = process.env.PORT; + } + + this._stats = $stats; + + logger = Util.logger('Express'); + + this._app = express(); + this._server = null; } // set/get server port -HttpFramework_Express.prototype.protocol = function () { - return 'http' + (this._options.credentials ? 's' : '') + ':'; +HttpFrameworkExpress.prototype.protocol = function () { + return 'http' + (this._options.credentials ? 's' : '') + ':'; }; // set/get server port -HttpFramework_Express.prototype.port = function (nPort) { - if (nPort) { - this._options.port = nPort; - } +HttpFrameworkExpress.prototype.port = function (nPort) { + if (nPort) { + this._options.port = nPort; + } - return this._options.port; + return this._options.port; }; // load all services -HttpFramework_Express.prototype.load = function () { - logger.group('Express HttpFramework Loading...'); - - // add promise wrapper - return when.promise(function (resolve, reject) { - // ------------------------------------------------ - - try { - this._app.set('port', this._options.port); - logger.info('Using Port', this._app.get('port')); - - if (!this._options.silent) { - this._app.use(this._getExpressLogger()); - } - - this._app.use(methodOverride()); - - if (this._options.env === 'dev') { - logger.info('Enabling Error Logging'); - this._app.use(errorHandler({ showStack: true, dumpExceptions: true })); - } - if (this._options.compress) { - logger.info('Enabling Compression'); - this._app.use(compress()); - } - if (this._options.urlencoded) { - logger.info('Enabling URL Encoding'); - this._app.use(bodyParser.urlencoded({ limit: '100mb', extended: true })); - } - if (this._options.parser.cookies) { - logger.info('Enabling Cookie Parser'); - this._app.use(cookieParser()); - } - if (this._options.parser.json) { - logger.info('Enabling JSON support'); - this._app.use(bodyParser.json({ limit: '100mb' })); - } +HttpFrameworkExpress.prototype.load = function () { + logger.group('Express HttpFramework Loading...'); + + // add promise wrapper + return when.promise(function (resolve, reject) { + // ------------------------------------------------ + + try { + this._app.set('port', this._options.port); + logger.info('Using Port', this._app.get('port')); + + if (!this._options.silent) { + this._app.use(this._getExpressLogger()); + } + + this._app.use(methodOverride()); + + if (this._options.env === 'dev') { + logger.info('Enabling Error Logging'); + this._app.use(errorHandler({ showStack: true, dumpExceptions: true })); + } + if (this._options.compress) { + logger.info('Enabling Compression'); + this._app.use(compress()); + } + if (this._options.urlencoded) { + logger.info('Enabling URL Encoding'); + this._app.use(bodyParser.urlencoded({ limit: '100mb', extended: true })); + } + if (this._options.parser.cookies) { + logger.info('Enabling Cookie Parser'); + this._app.use(cookieParser()); + } + if (this._options.parser.json) { + logger.info('Enabling JSON support'); + this._app.use(bodyParser.json({ limit: '100mb' })); + } + + if (this._options.session) { + logger.info('Enabling Sessions'); + + var defaultSession = { + secret: Util.string.random(32), + resave: false, // depends on the session store, see https://github.com/expressjs/session#resave + saveUninitialized: false, // depends on several cases, see https://github.com/expressjs/session#saveuninitialized + cookie: { + // TODO: auto enable "secure: true" only if https + path: '/', + httpOnly: true, + maxAge: 1000 * 60 * 24 // 24 hours + }, + storeInst: new session.MemoryStore() + }; + + // if this._options.session no object then make default settings + if (!_.isObject(this._options.session)) { + this._options.session = defaultSession; + } else { + this._options.session = _.merge(defaultSession, this._options.session); + } - if (this._options.session) { - logger.info('Enabling Sessions'); - - var defaultSession = { - secret: Util.string.random(32), - resave: false, // depends on the session store, see https://github.com/expressjs/session#resave - saveUninitialized: false, // depends on several cases, see https://github.com/expressjs/session#saveuninitialized - cookie: { - // TODO: auto enable "secure: true" only if https - path: '/', - httpOnly: true, - maxAge: 1000 * 60 * 24 // 24 hours - }, - storeInst: new session.MemoryStore() - }; - - // if this._options.session no object then make default settings - if (!_.isObject(this._options.session)) { - this._options.session = defaultSession; - } else { - this._options.session = _.merge(defaultSession, this._options.session); - } - - this._app.use(session(this._options.session)); - } + this._app.use(session(this._options.session)); + } - resolve(); - logger.groupEnd(''); - } catch (err) { - reject(err); - logger.groupEnd(''); - } + resolve(); + logger.groupEnd(''); + } catch (err) { + reject(err); + logger.groupEnd(''); + } - // ------------------------------------------------ - }.bind(this)); - // end promise wrapper + // ------------------------------------------------ + }.bind(this)); + // end promise wrapper }; -HttpFramework_Express.prototype.validateMethod = function (method) { - if (!this._app[method] || !_.isFunction(this._app[method])) { - logger.warn("ServiceManager: Invalid method", method); - return false; - } else { - return true; - } +HttpFrameworkExpress.prototype.validateMethod = function (method) { + if (!this._app[method] || !_.isFunction(this._app[method])) { + logger.warn('ServiceManager: Invalid method', method); + return false; + } else { + return true; + } }; -HttpFramework_Express.prototype.getName = function () { - return 'express'; +HttpFrameworkExpress.prototype.getName = function () { + return 'express'; }; -HttpFramework_Express.prototype.app = function () { - return this._app; +HttpFrameworkExpress.prototype.app = function () { + return this._app; }; /* -HttpFramework_Express.prototype.server = function() { +HttpFrameworkExpress.prototype.server = function() { return this._server; }; */ -HttpFramework_Express.prototype.addMethodFunction = function (method, middlewareList, routeStr, handler) { - - var validMiddlewares = []; - if (middlewareList) { - for (var i = 0; i < middlewareList.length; i++) { - // if plugin has isType, is express and has setupRoute function - // filter out all invalid plugins - if (middlewareList[i] && middlewareList[i].middleware && _.isFunction(middlewareList[i].middleware.isType) && middlewareList[i].middleware.isType('express') && _.isFunction(middlewareList[i].middleware.setupRoute)) { - - validMiddlewares.push(middlewareList[i]); - } else { - // missing isType or - // is not express or - // setupRoute function - } - } +HttpFrameworkExpress.prototype.addMethodFunction = function (method, middlewareList, routeStr, handler) { + var validMiddlewares = []; + if (middlewareList) { + for (var i = 0; i < middlewareList.length; i++) { + // if plugin has isType, is express and has setupRoute function + // filter out all invalid plugins + if (middlewareList[i] && middlewareList[i].middleware && _.isFunction(middlewareList[i].middleware.isType) && middlewareList[i].middleware.isType('express') && _.isFunction(middlewareList[i].middleware.setupRoute)) { + validMiddlewares.push(middlewareList[i]); + } else { + // missing isType or + // is not express or + // setupRoute function + } } + } - if (validMiddlewares && _.isArray(validMiddlewares) && validMiddlewares.length) { - - // run setupRoute for each plugin - _.forEach(validMiddlewares, function (validMiddleware) { - validMiddleware.middleware.setupRoute(this._app, method, routeStr, handler, validMiddleware.options); - }.bind(this)); - } + if (validMiddlewares && _.isArray(validMiddlewares) && validMiddlewares.length) { + // run setupRoute for each plugin + _.forEach(validMiddlewares, function (validMiddleware) { + validMiddleware.middleware.setupRoute(this._app, method, routeStr, handler, validMiddleware.options); + }.bind(this)); + } - this._app[method](routeStr, handler); + this._app[method](routeStr, handler); }; -HttpFramework_Express.prototype.addStaticDir = function (staticDir, staticRoute) { - if (staticRoute) { - return this._app.use(staticRoute, express.static(staticDir)); - } else { - return this._app.use(express.static(staticDir)); - } +HttpFrameworkExpress.prototype.addStaticDir = function (staticDir, staticRoute) { + if (staticRoute) { + return this._app.use(staticRoute, express.static(staticDir)); + } else { + return this._app.use(express.static(staticDir)); + } }; -HttpFramework_Express.prototype.addStaticFile = function (staticRoute, staticFile) { - this._app.get(staticRoute, function (req, res) { - res.sendFile(path.resolve(staticFile)); - }.bind(this)); +HttpFrameworkExpress.prototype.addStaticFile = function (staticRoute, staticFile) { + this._app.get(staticRoute, function (req, res) { + res.sendFile(path.resolve(staticFile)); + }); }; -HttpFramework_Express.prototype.addStaticFileDefault = function (staticFile) { - this._app.use(function (req, res) { - res.sendFile(path.resolve(staticFile)); - }.bind(this)); +HttpFrameworkExpress.prototype.addStaticFileDefault = function (staticFile) { + this._app.use(function (req, res) { + res.sendFile(path.resolve(staticFile)); + }); }; -HttpFramework_Express.prototype.addRedirect = function (from, to) { - return this._app.use(from, function (req, res) { - res.redirect(to); - }.bind(this)); +HttpFrameworkExpress.prototype.addRedirect = function (from, to) { + return this._app.use(from, function (req, res) { + res.redirect(to); + }); }; // custom logging function to add 'x-forwarded-for' and defaults for missing values -HttpFramework_Express.prototype._getExpressLogger = function () { - morgan.token('remote-addy', function (req, res) { - if (req.headers.hasOwnProperty('x-forwarded-for')) { - return req.headers['x-forwarded-for']; - } else { - return req.connection.remoteAddress; - } - }); - - /* - var logFormat = ':remote-addy - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" (:response-time ms)'; - return express.logger(logFormat); - */ - return morgan(function (t, req, res) { - var rTime = t['response-time'](req, res); - var contentLength = t.res(req, res, 'content-length'); - var status = t.status(req, res); - var url = t.url(req, res); - - return t['remote-addy'](req, res) + ' - - [' + t.date(req, res) + '] "' + t.method(req, res) + ' ' + url + ' HTTP/' + t['http-version'](req, res) + '" ' + status + ' ' + (contentLength || '-') + ' "' + (t.referrer(req, res) || '-') + '" "' + (t['user-agent'](req, res) || '-') + '" (' + rTime + ' ms)'; - }); +HttpFrameworkExpress.prototype._getExpressLogger = function () { + morgan.token('remote-addy', function (req, res) { + if (req.headers.hasOwnProperty('x-forwarded-for')) { + return req.headers['x-forwarded-for']; + } else { + return req.connection.remoteAddress; + } + }); + + /* + var logFormat = ':remote-addy - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" (:response-time ms)'; + return express.logger(logFormat); + */ + return morgan(function (t, req, res) { + var rTime = t['response-time'](req, res); + var contentLength = t.res(req, res, 'content-length'); + var status = t.status(req, res); + var url = t.url(req, res); + + return t['remote-addy'](req, res) + ' - - [' + t.date(req, res) + '] "' + t.method(req, res) + ' ' + url + ' HTTP/' + t['http-version'](req, res) + '" ' + status + ' ' + (contentLength || '-') + ' "' + (t.referrer(req, res) || '-') + '" "' + (t['user-agent'](req, res) || '-') + '" (' + rTime + ' ms)'; + }); }; // inject dependency from controller function DI -HttpFramework_Express.prototype.buildInputs = function ($rawRequest) { - // POST - req.body - // GET - req.query - // GET - req.params - return _.pick($rawRequest, ["query", "params", "body"]); +HttpFrameworkExpress.prototype.buildInputs = function ($rawRequest) { + // POST - req.body + // GET - req.query + // GET - req.params + return _.pick($rawRequest, ['query', 'params', 'body']); }; // type == "view" // route.outContentType // templateFunc -HttpFramework_Express.prototype.addWrappedMethodFunction = function (method, middlewareList, routeStr, handler) { - - this.addMethodFunction(method, middlewareList, routeStr, function (req, res, next) { - var responded = false; - - handler(this.buildInputs(req), req.session, req.cookies, req, res, next).then(function (output) { - // --------------------------------------- - // TODO: Custom error format, defined in config - if (responded) { - logger.warn("Already responded to request"); - return; - } +HttpFrameworkExpress.prototype.addWrappedMethodFunction = function (method, middlewareList, routeStr, handler) { + this.addMethodFunction(method, middlewareList, routeStr, function (req, res, next) { + var responded = false; + + handler(this.buildInputs(req), req.session, req.cookies, req, res, next).then(function (output) { + // --------------------------------------- + // TODO: Custom error format, defined in config + if (responded) { + logger.warn('Already responded to request'); + return; + } + + responded = true; + if (!output.headers || !_.isObject(output.headers)) { + output.headers = {}; + } + + if (output.headers.filename) { + var mimetype = mime.lookup(output.headers.filename); + if (!output.headers.hasOwnProperty('Content-type')) { + output.headers['Content-type'] = mimetype; + } + if (!output.headers.hasOwnProperty('Content-disposition')) { + output.headers['Content-disposition'] = 'attachment; filename=' + output.headers.filename; + } + } - responded = true; - if (!output.headers || !_.isObject(output.headers)) { - output.headers = {}; - } + // is not buffer and is object + if (!Buffer.isBuffer(output.data) && _.isObject(output.data)) { + // assume JSON + if (!output.headers.hasOwnProperty('Content-type')) { + output.headers['Content-Type'] = 'application/json'; + } + // convert object to string + output.data = (0, _stringify2.default)(output.data); + } else if (_.isString(output.data)) { + // assume HTML + if (!output.headers.hasOwnProperty('Content-type')) { + output.headers['Content-Type'] = 'text/html'; + } + } else {} + // ??? - if (output.headers.filename) { - var mimetype = mime.lookup(output.headers.filename); - if (!output.headers.hasOwnProperty('Content-type')) { - output.headers['Content-type'] = mimetype; - } - if (!output.headers.hasOwnProperty('Content-disposition')) { - output.headers['Content-disposition'] = 'attachment; filename=' + output.headers.filename; - } - } - // is not buffer and is object - if (!Buffer.isBuffer(output.data) && _.isObject(output.data)) { - - // assume JSON - if (!output.headers.hasOwnProperty('Content-type')) { - output.headers['Content-Type'] = "application/json"; - } - // convert object to string - output.data = (0, _stringify2.default)(output.data); - } else if (_.isString(output.data)) { - // assume HTML - if (!output.headers.hasOwnProperty('Content-type')) { - output.headers['Content-Type'] = "text/html"; - } - } else {} - // ??? - - - // if not code passed in, default 200 - if (!output.code) { - output.code = 200; - } + // if not code passed in, default 200 + if (!output.code) { + output.code = 200; + } - // merge default content-type with headers - res.writeHead(output.code, output.headers); + // merge default content-type with headers + res.writeHead(output.code, output.headers); - if (Buffer.isBuffer(output.data)) { - res.end(output.data, 'binary'); - } else { - res.end(output.data); - } + if (Buffer.isBuffer(output.data)) { + res.end(output.data, 'binary'); + } else { + res.end(output.data); + } - // TOOD: duplicate setHeader error with proper pipeline - //next(); - }.bind(this)); - }.bind(this)); + // TOOD: duplicate setHeader error with proper pipeline + // next(); + }); + }.bind(this)); }; /** @@ -329,42 +324,40 @@ HttpFramework_Express.prototype.addWrappedMethodFunction = function (method, mid * @returns {Array} * @private */ -HttpFramework_Express.prototype.validateInputs = function (cInput, req) { - var errors = []; - - for (var i in cInput) { - //logger.log("_validateInputs:" , i); - - // check input type - if (req.hasOwnProperty(i)) { - - for (var k in cInput[i]) { - // check required - if (!req[i].hasOwnProperty(k) && cInput[i][k].required) { - // missing - errors.push({ error: "Missing " + i + " " + k, type: "missing", id: k }); - } - // check type - else if (req[i].hasOwnProperty(k) && cInput[i][k].type) { - - var tFuncName = "is" + util.String.capitalize(cInput[i][k].type); - // check if lodash has type function - if (_[tFuncName]) { - // check if input passes type function - if (!_[tFuncName](req[i][k])) { - errors.push({ error: "Invalid input " + k + " with value " + req[i][k] + ", expecting type " + i, type: "invalid", id: k }); - } - } - } - } +HttpFrameworkExpress.prototype.validateInputs = function (cInput, req) { + var errors = []; + + for (var i in cInput) { + // logger.log("_validateInputs:" , i); + + // check input type + if (req.hasOwnProperty(i)) { + for (var k in cInput[i]) { + // check required + if (!req[i].hasOwnProperty(k) && cInput[i][k].required) { + // missing + errors.push({ error: 'Missing ' + i + ' ' + k, type: 'missing', id: k }); } + // check type + else if (req[i].hasOwnProperty(k) && cInput[i][k].type) { + var tFuncName = 'is' + Util.String.capitalize(cInput[i][k].type); + // check if lodash has type function + if (_[tFuncName]) { + // check if input passes type function + if (!_[tFuncName](req[i][k])) { + errors.push({ error: 'Invalid input ' + k + ' with value ' + req[i][k] + ', expecting type ' + i, type: 'invalid', id: k }); + } + } + } + } } - - if (errors.length === 0) { - errors = undefined; - } - if (errors.length === 1) { - errors = errors[0]; - } - return errors; + } + + if (errors.length === 0) { + errors = undefined; + } + if (errors.length === 1) { + errors = errors[0]; + } + return errors; }; \ No newline at end of file diff --git a/legacy/hyper.js b/legacy/hyper.js index 3e3e81c..30a5d8c 100644 --- a/legacy/hyper.js +++ b/legacy/hyper.js @@ -26,16 +26,15 @@ var _create2 = _interopRequireDefault(_create); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var fs = require('fs'); var path = require('path'); var http = require('http'); var _ = require('lodash'); -var transfuser = require('transfuser'); var when = require('when'); +var Transfuser = require('transfuser'); // -var HttpFramework_Express = require('./http.framework.express.js'); +var HttpFrameworkExpress = require('./http.framework.express.js'); // var PluginManager = require('yanpm'); var ServiceManager = require('./manager.service.js'); @@ -65,292 +64,293 @@ module.exports = Hyper; */ function Hyper(options) { - if (!(this instanceof Hyper)) { - // singleton behavior - if (!_hyper) { - _hyper = new Hyper(options); - } - return _hyper; - } - - // default options - if (!options) { - options = {}; + if (!(this instanceof Hyper)) { + // singleton behavior + if (!_hyper) { + _hyper = new Hyper(options); } - - this._displayDebuggerInfo = options.displayDebuggerInfo || false; - - // default - var configs = ['$/config.json', // framework dir (default) - '$/config.js' // framework dir (default) - ]; - - // get server filename - this._defaultAppName = options.appName || path.basename(require.main.filename, '.js'); - - configs.push('config.json'); // current dir - configs.push('config.js'); // current dir - configs.push(this._defaultAppName + '.config.json'); // current dir - configs.push(this._defaultAppName + '.config.js'); // current dir - - configs.push('~/config.custom.json'); // home dir - configs.push('~/config.custom.js'); // home dir - configs.push('~/' + this._defaultAppName + '.config.custom.json'); // home dir - configs.push('~/' + this._defaultAppName + '.config.custom.js'); // home dir - - this._options = _.merge({ - configs: configs - }, options); - - // TODO: add stats - this._stats = null; - this._httpFramework = null; - this._httpServer = null; - this._servicesManifest = {}; - this._isLoaded = false; - - // set logger - logger = util.logger("HyperCore"); - - // ------------------------------ - // normalize options - this._options = this._normalizeOptions(this._options); - //logger.info('options:', JSON.stringify(this._options, null, 2)); - // ------------------------------ - - // middleware manager - this._pluginManager = new PluginManager({ - logger: logger - }); - - this._serviceMiddlewareManager = new ServiceMiddlewareManager(); - // default service middleware - this._serviceMiddlewareManager.add('defaultRoutes'); - this._serviceMiddlewareManager.add('apiviewRoutes'); - - // add catch all, just in case - process.on('uncaughtException', function (err) { - logger.error("Uncaught Error -", err, ", stack:", err.stack); - }); + return _hyper; + } + + // default options + if (!options) { + options = {}; + } + + this._displayDebuggerInfo = options.displayDebuggerInfo || false; + + // default + var configs = ['$/config.json', // framework dir (default) + '$/config.js' // framework dir (default) + ]; + + // get server filename + this._defaultAppName = options.appName || path.basename(require.main.filename, '.js'); + + configs.push('config.json'); // current dir + configs.push('config.js'); // current dir + configs.push(this._defaultAppName + '.config.json'); // current dir + configs.push(this._defaultAppName + '.config.js'); // current dir + + configs.push('~/config.custom.json'); // home dir + configs.push('~/config.custom.js'); // home dir + configs.push('~/' + this._defaultAppName + '.config.custom.json'); // home dir + configs.push('~/' + this._defaultAppName + '.config.custom.js'); // home dir + + this._options = _.merge({ + configs: configs + }, options); + + // TODO: add stats + this._stats = null; + this._httpFramework = null; + this._httpServer = null; + this._servicesManifest = {}; + this._isLoaded = false; + + // set logger + logger = util.logger('HyperCore'); + + // ------------------------------ + // normalize options + this._options = this._normalizeOptions(this._options); + // logger.info('options:', JSON.stringify(this._options, null, 2)); + // ------------------------------ + + // middleware manager + this._pluginManager = new PluginManager({ + logger: logger + }); + + this._serviceMiddlewareManager = new ServiceMiddlewareManager(); + // default service middleware + this._serviceMiddlewareManager.add('defaultRoutes'); + this._serviceMiddlewareManager.add('apiviewRoutes'); + + // add catch all, just in case + process.on('uncaughtException', function (err) { + logger.error('Uncaught Error -', err, ', stack:', err.stack); + }); } Hyper.prototype.env = function (env) { - if (env) { - - this._options.serviceManager.env = env; - this._options.httpFramework.env = env; - } + if (env) { + this._options.serviceManager.env = env; + this._options.httpFramework.env = env; + } - return this._options.serviceManager.env; + return this._options.serviceManager.env; }; Hyper.prototype._normalizeOptions = function (options) { - options = _.merge({ - serviceManager: { - env: 'dev', - silent: false, - displayDebuggerInfo: false - }, - httpFramework: { - env: 'dev', - port: 8000, - silent: false, - displayDebuggerInfo: false - }, - hyper: { - displayDebuggerInfo: false - } - }, options); - - if (options.env) { - options.serviceManager.env = options.env; - options.httpFramework.env = options.env; - delete options.env; - } - if (options.port) { - options.httpFramework.port = options.port; - delete options.port; - } - if (options.session) { - options.httpFramework.session = options.session; - delete options.session; - } - if (options.hasOwnProperty('displayDebuggerInfo')) { - options.hyper.displayDebuggerInfo = options.displayDebuggerInfo; - options.httpFramework.displayDebuggerInfo = options.displayDebuggerInfo; - options.serviceManager.displayDebuggerInfo = options.displayDebuggerInfo; - delete options.displayDebuggerInfo; + options = _.merge({ + serviceManager: { + env: 'dev', + silent: false, + displayDebuggerInfo: false + }, + httpFramework: { + env: 'dev', + port: 8000, + silent: false, + displayDebuggerInfo: false + }, + hyper: { + displayDebuggerInfo: false } - if (options.silent) { - options.httpFramework.silent = true; - options.serviceManager.silent = true; - delete options.silent; - - logger.setEnv('prod'); - } - - return options; + }, options); + + if (options.env) { + options.serviceManager.env = options.env; + options.httpFramework.env = options.env; + delete options.env; + } + if (options.port) { + options.httpFramework.port = options.port; + delete options.port; + } + if (options.session) { + options.httpFramework.session = options.session; + delete options.session; + } + if (options.hasOwnProperty('displayDebuggerInfo')) { + options.hyper.displayDebuggerInfo = options.displayDebuggerInfo; + options.httpFramework.displayDebuggerInfo = options.displayDebuggerInfo; + options.serviceManager.displayDebuggerInfo = options.displayDebuggerInfo; + delete options.displayDebuggerInfo; + } + if (options.silent) { + options.httpFramework.silent = true; + options.serviceManager.silent = true; + delete options.silent; + + logger.setEnv('prod'); + } + + return options; }; Hyper.prototype.logger = function () { - return util.logger(); + return util.logger(); }; -Hyper.prototype.resource = function (name, resourceModule) { - this._serviceManager.addResource(name, resourceModule); +Hyper.prototype.resource = function () { + var _serviceManager; + + (_serviceManager = this._serviceManager).addResource.apply(_serviceManager, arguments); }; Hyper.prototype._loadConfigs = function (servicesManifest) { - // config manager - // logger not loaded, yet so we can only user console - logger.log('---------------------------------------------'); - logger.group('Loading Configuration...'); - this._configManager = new transfuser({ - basePath: __dirname, - logger: logger - }); - // blocking, but this is ok because the server needs the configs to proceed - this._config = this._configManager.loadSync(this._options.configs, !this._displayDebuggerInfo); - // normalize configs - this._config = this._normalizeOptions(this._config); - logger.groupEnd(""); - - // add options passed in from inits - this._config.appName = this._options.appName; - this._config.hyper = _.merge(this._config.hyper, this._options.hyper); - this._config.serviceManager = _.merge(this._config.serviceManager, this._options.serviceManager); - this._config.httpFramework = _.merge(this._config.httpFramework, this._options.httpFramework); - // TODO: add to verbose - // logger.info('config:', JSON.stringify(this._config, null, 2)); - - // - if (this._config.hyper.hasOwnProperty('displayDebuggerInfo')) { - this._displayDebuggerInfo = this._config.hyper.displayDebuggerInfo; - } - - // update logger options, using config - logger.setOptions(this._config.hyper.logger); - - // service config - this._servicesManifest = servicesManifest; + // config manager + // logger not loaded, yet so we can only user console + logger.log('---------------------------------------------'); + logger.group('Loading Configuration...'); + this._configManager = new Transfuser({ + basePath: __dirname, + logger: logger + }); + // blocking, but this is ok because the server needs the configs to proceed + this._config = this._configManager.loadSync(this._options.configs, !this._displayDebuggerInfo); + // normalize configs + this._config = this._normalizeOptions(this._config); + logger.groupEnd(''); + + // add options passed in from inits + this._config.appName = this._options.appName; + this._config.hyper = _.merge(this._config.hyper, this._options.hyper); + this._config.serviceManager = _.merge(this._config.serviceManager, this._options.serviceManager); + this._config.httpFramework = _.merge(this._config.httpFramework, this._options.httpFramework); + // TODO: add to verbose + // logger.info('config:', JSON.stringify(this._config, null, 2)); + + // + if (this._config.hyper.hasOwnProperty('displayDebuggerInfo')) { + this._displayDebuggerInfo = this._config.hyper.displayDebuggerInfo; + } + + // update logger options, using config + logger.setOptions(this._config.hyper.logger); + + // service config + this._servicesManifest = servicesManifest; }; // load services // return promise Hyper.prototype.load = function (servicesManifest) { - // add promise wrapper - return when.promise(function (resolve) { - // ------------------------------------------------ - this._isLoaded = true; + // add promise wrapper + return when.promise(function (resolve) { + // ------------------------------------------------ + this._isLoaded = true; - this._loadConfigs(servicesManifest); + this._loadConfigs(servicesManifest); - this._initHttpFramework(); + this._initHttpFramework(); - // init service manager and router - this._initServiceManager(); + // init service manager and router + this._initServiceManager(); - //logger.info("process:", JSON.stringify(process.versions, null, 2)); + // logger.info("process:", JSON.stringify(process.versions, null, 2)); - // done loading plugins, now load http framework - this._serviceManager.loadHttpFramework().then(function () { - resolve(this); - }.bind(this)); - // ------------------------------------------------ + // done loading plugins, now load http framework + this._serviceManager.loadHttpFramework().then(function () { + resolve(this); }.bind(this)); - // end promise wrapper + // ------------------------------------------------ + }.bind(this)); + // end promise wrapper }; Hyper.prototype.httpServerListen = function () { - // add promise wrapper - return when.promise(function (resolve, reject) { - // ------------------------------------------------ + // add promise wrapper + return when.promise(function (resolve, reject) { + // ------------------------------------------------ - this._httpServer.listen(this._httpFramework.port(), function () { - logger.log('Listening on port %d', this._httpFramework.port()); - resolve(); - }.bind(this)); - - // ------------------------------------------------ + this._httpServer.listen(this._httpFramework.port(), function () { + logger.log('Listening on port %d', this._httpFramework.port()); + resolve(); }.bind(this)); - // end promise wrapper + + // ------------------------------------------------ + }.bind(this)); + // end promise wrapper }; // load all services and then start Hyper.prototype._start = function () { - return this._serviceManager.loadServices().then(function () { - return this.httpServerListen(); - }.bind(this)).then(function () { - return this._serviceManager.postStartInit(); - }.bind(this)).then(function () { - logger.log('---------------------------------------------'); - logger.log('Ready to accept connections on port', this._httpFramework.port()); - logger.log('---------------------------------------------'); - return this; - }.bind(this)); + return this._serviceManager.loadServices().then(function () { + return this.httpServerListen(); + }.bind(this)).then(function () { + return this._serviceManager.postStartInit(); + }.bind(this)).then(function () { + logger.log('---------------------------------------------'); + logger.log('Ready to accept connections on port', this._httpFramework.port()); + logger.log('---------------------------------------------'); + return this; + }.bind(this)); }; Hyper.prototype.start = function (servicesManifest) { - if (this._isLoaded) { - logger.log('---------------------------------------------'); - return this._start(); - } else { - return this.load(servicesManifest).then(function () { - logger.log('---------------------------------------------'); - return this._start(); - }.bind(this)); - } + if (this._isLoaded) { + logger.log('---------------------------------------------'); + return this._start(); + } else { + return this.load(servicesManifest).then(function () { + logger.log('---------------------------------------------'); + return this._start(); + }.bind(this)); + } }; Hyper.prototype.stop = function () { - // add promise wrapper - return when.promise(function (resolve, reject) { - // ------------------------------------------------ + // add promise wrapper + return when.promise(function (resolve, reject) { + // ------------------------------------------------ - this._httpServer.close(); - resolve(); + this._httpServer.close(); + resolve(); - // ------------------------------------------------ - }.bind(this)); - // end promise wrapper + // ------------------------------------------------ + }.bind(this)); + // end promise wrapper }; // TODO: merge use and middleware Hyper.prototype.use = function (MiddlewareGroup, MiddlewareName, option) { - this._pluginManager.add(MiddlewareGroup, MiddlewareName, option); + this._pluginManager.add(MiddlewareGroup, MiddlewareName, option); }; Hyper.prototype.middleware = function (serviceMiddleware, serviceMiddlewareConfig) { - this._serviceMiddlewareManager.add(serviceMiddleware, serviceMiddlewareConfig); + this._serviceMiddlewareManager.add(serviceMiddleware, serviceMiddlewareConfig); }; Hyper.prototype.httpFramework = function () { - return this._httpFramework; + return this._httpFramework; }; Hyper.prototype.httpServer = function () { - return this._httpServer; + return this._httpServer; }; Hyper.prototype.services = function () { - return this._serviceManager.getServiceRouter(); + return this._serviceManager.getServiceRouter(); }; Hyper.prototype._initHttpFramework = function () { - // load HTTP framework - if (this._config.hyper.httpFramework === 'express') { - // TODO: use DI to pass vars - this._httpFramework = new HttpFramework_Express(this._config.httpFramework, this._stats); - } else { - logger.error("Uncaught Error -", err, ", stack:", err.stack); - return; - } - - this._httpServer = http.Server(this._httpFramework.app()); + // load HTTP framework + if (this._config.hyper.httpFramework === 'express') { + // TODO: use DI to pass vars + this._httpFramework = new HttpFrameworkExpress(this._config.httpFramework, this._stats); + } else { + logger.error('Unknown HTTP Framework'); + return; + } + + this._httpServer = http.Server(this._httpFramework.app()); }; Hyper.prototype._initServiceManager = function () { - // service manager - this._serviceManager = new ServiceManager(this, this._config, this._servicesManifest, this._pluginManager, this._serviceMiddlewareManager, this._httpFramework, this._defaultAppName); + // service manager + this._serviceManager = new ServiceManager(this, this._config, this._servicesManifest, this._pluginManager, this._serviceMiddlewareManager, this._httpFramework, this._defaultAppName); }; Hyper.export = {}; @@ -359,94 +359,94 @@ Hyper.classes = {}; Hyper.util = {}; Hyper.export.service = function (serviceName) { - return ServiceManager.export(serviceName); + return ServiceManager.export(serviceName); }; Hyper.util.extends = function (dest, src) { - dest.prototype = (0, _create2.default)(src.prototype); - dest.prototype.constructor = dest; - return src.prototype; + dest.prototype = (0, _create2.default)(src.prototype); + dest.prototype.constructor = dest; + return src.prototype; }; Hyper.decor.handler = function (config) { - return function (target, key, descriptor) { - if (!target.$route) { - target.$route = {}; - } - target.$route[key] = config; - }; + return function (target, key, descriptor) { + if (!target.$route) { + target.$route = {}; + } + target.$route[key] = config; + }; }; // TODO: finish this Hyper.classes.controller = function () { - function _class() { - (0, _classCallCheck3.default)(this, _class); + function _class() { + (0, _classCallCheck3.default)(this, _class); + + this.$route = {}; + } + (0, _createClass3.default)(_class, [{ + key: '$routeInit', + value: function $routeInit($logger) { + // create route object if not exist + if (!this.$route) { this.$route = {}; - } + } - (0, _createClass3.default)(_class, [{ - key: '$routeInit', - value: function $routeInit($logger) { - // create route object if not exist - if (!this.$route) { - this.$route = {}; - } - - var proto = (0, _getPrototypeOf2.default)(this); - // console.log('proto:', proto); - - // find list of all handler - var pList = (0, _getOwnPropertyNames2.default)(proto); - var list = pList.filter(function (p) { - return p !== 'constructor' && typeof this[p] === 'function'; - }.bind(this)); - // console.log('pList:', pList, ', list:', list); - - // get route configs for all handlers - for (var i = 0; i < list.length; i++) { - this.__getHandlerRouteConfig($logger, list[i]); - } - - console.log('$route:', this.$route); - } - }, { - key: '__getHandlerRouteConfig', - value: function __getHandlerRouteConfig($logger, handlerName) { - var funcStr = this[handlerName].toString(); - // TODO: test all valid JSON string - var re = /\@Hyper\.route\(([:;{}<>|"',. !@#$%^&*\?\/\[\]\-\n\r\t\b\^0-9a-zA-Z]*)\)/g; - - var reResult = re.exec(funcStr); - console.log('funcStr:', funcStr); - console.log('regex result:', reResult); - if (reResult && reResult.length >= 2) { - config = reResult[1]; - - // strip start line comments - config = config.replace(/^[ \t]*\/\//mg, ''); - - try { - config = JSON.parse(config); - } catch (err) { - console.error('$routeInit Error:', err); - } - - this.$route[handlerName] = config; - } + var proto = (0, _getPrototypeOf2.default)(this); + // console.log('proto:', proto); + + // find list of all handler + var pList = (0, _getOwnPropertyNames2.default)(proto); + var list = pList.filter(function (p) { + return p !== 'constructor' && typeof this[p] === 'function'; + }.bind(this)); + // console.log('pList:', pList, ', list:', list); + + // get route configs for all handlers + for (var i = 0; i < list.length; i++) { + this.__getHandlerRouteConfig($logger, list[i]); + } + + console.log('$route:', this.$route); + } + }, { + key: '__getHandlerRouteConfig', + value: function __getHandlerRouteConfig($logger, handlerName) { + var funcStr = this[handlerName].toString(); + // TODO: test all valid JSON string + var re = /@Hyper\.route\(([:;{}<>|"',. !@#$%^&*\?\/\[\]\-\n\r\t\b\^0-9a-zA-Z]*)\)/g; + + var reResult = re.exec(funcStr); + console.log('funcStr:', funcStr); + console.log('regex result:', reResult); + if (reResult && reResult.length >= 2) { + var config = reResult[1]; + + // strip start line comments + config = config.replace(/^[ \t]*\/\//mg, ''); + + try { + config = JSON.parse(config); + } catch (err) { + console.error('$routeInit Error:', err); } - }, { - key: '$init', - value: function $init() {} - }, { - key: '$postInit', - value: function $postInit() {} - }, { - key: '$preRoute', - value: function $preRoute() {} - }, { - key: '$postRoute', - value: function $postRoute() {} - }]); - return _class; + + this.$route[handlerName] = config; + } + } + }, { + key: '$init', + value: function $init() {} + }, { + key: '$postInit', + value: function $postInit() {} + }, { + key: '$preRoute', + value: function $preRoute() {} + }, { + key: '$postRoute', + value: function $postRoute() {} + }]); + return _class; }(); \ No newline at end of file diff --git a/legacy/manager.middleware.js b/legacy/manager.middleware.js index 1f526dd..1ad2c55 100644 --- a/legacy/manager.middleware.js +++ b/legacy/manager.middleware.js @@ -6,9 +6,8 @@ */ var fs = require('fs'); -// var _ = require('lodash'); -// + var util = require('./util.js'); var logger = null; @@ -19,11 +18,11 @@ module.exports = Middleware; * Constructor * --------------------------------------------------- */ function Middleware() { - logger = util.logger('Middleware'); + logger = util.logger('Middleware'); - this.middleware = {}; + this.middleware = {}; - this.defaultmiddleware = {}; + this.defaultmiddleware = {}; } /* --------------------------------------------------- @@ -42,211 +41,209 @@ function Middleware() { */ Middleware.prototype.use = function (MiddlewareGroup, MiddlewareName, option) { - if (_.isString(option) && option === 'default') { - - // check if already default - var defaultMiddleware = this.getDefault(MiddlewareGroup); - - // if default Middleware not exist then set it - // OR - // not name the same - if (!defaultMiddleware || defaultMiddleware && defaultMiddleware.name != MiddlewareName) { - defaultMiddleware = this._setDefault(MiddlewareGroup, MiddlewareName); - // default was added - if (defaultMiddleware) { - return defaultMiddleware.Middleware; - } else { - // problem with Middleware - // error already reported upstream - } - } - } - - var Middleware = null; - // Middleware.use('ejs'); - if (_.isString(MiddlewareGroup) && !MiddlewareName) { - // find Middleware file, load it - Middleware = this._loadMiddlewareFile(null, MiddlewareName); + if (_.isString(option) && option === 'default') { + // check if already default + var defaultMiddleware = this.getDefault(MiddlewareGroup); + + // if default Middleware not exist then set it + // OR + // not name the same + if (!defaultMiddleware || defaultMiddleware && defaultMiddleware.name !== MiddlewareName) { + defaultMiddleware = this._setDefault(MiddlewareGroup, MiddlewareName); + // default was added + if (defaultMiddleware) { + return defaultMiddleware.Middleware; + } else { + // problem with Middleware + // error already reported upstream + } } - // Middleware.use('template', 'ejs'); - // Middleware.use('template', './lib/middleware/ejs.js'); - else if (_.isString(MiddlewareGroup) && _.isString(MiddlewareName)) { - // find Middleware file, load it - Middleware = this._loadMiddlewareFile(MiddlewareGroup, MiddlewareName); - } - // Middleware.use(require('./lib/middleware/ejs.js')); - // var ejs = require('ejs'); - // Middleware.use(new ejs()); - else if (_.isFunction(MiddlewareGroup) || _.isObject(MiddlewareGroup)) { - Middleware = this._setMiddleware(MiddlewareGroup); - } else { - logger.warn("Middleware (" + MiddlewareGroup + ", " + MiddlewareName + ") invalid"); - } - - if (!Middleware) { - logger.info("Problem loading Middleware (" + MiddlewareGroup + ", " + MiddlewareName + ")"); + } + + var Middleware = null; + // Middleware.use('ejs'); + if (_.isString(MiddlewareGroup) && !MiddlewareName) { + // find Middleware file, load it + Middleware = this._loadMiddlewareFile(null, MiddlewareName); + } + // Middleware.use('template', 'ejs'); + // Middleware.use('template', './lib/middleware/ejs.js'); + else if (_.isString(MiddlewareGroup) && _.isString(MiddlewareName)) { + // find Middleware file, load it + Middleware = this._loadMiddlewareFile(MiddlewareGroup, MiddlewareName); } - - return Middleware; + // Middleware.use(require('./lib/middleware/ejs.js')); + // var ejs = require('ejs'); + // Middleware.use(new ejs()); + else if (_.isFunction(MiddlewareGroup) || _.isObject(MiddlewareGroup)) { + Middleware = this._setMiddleware(MiddlewareGroup); + } else { + logger.warn('Middleware (' + MiddlewareGroup + ', ' + MiddlewareName + ') invalid'); + } + + if (!Middleware) { + logger.info('Problem loading Middleware (' + MiddlewareGroup + ', ' + MiddlewareName + ')'); + } + + return Middleware; }; Middleware.prototype.get = function (MiddlewareGroup, MiddlewareName) { - return this._getMiddleware(MiddlewareGroup, MiddlewareName); + return this._getMiddleware(MiddlewareGroup, MiddlewareName); }; Middleware.prototype.getAll = function (MiddlewareGroup) { - if (this.middleware.hasOwnProperty(MiddlewareGroup)) { - return this.middleware[MiddlewareGroup]; - } - return null; + if (this.middleware.hasOwnProperty(MiddlewareGroup)) { + return this.middleware[MiddlewareGroup]; + } + return null; }; Middleware.prototype.getDefault = function (MiddlewareGroup) { - if (this.defaultmiddleware.hasOwnProperty(MiddlewareGroup)) { - return this.defaultmiddleware[MiddlewareGroup]; - } - return null; + if (this.defaultmiddleware.hasOwnProperty(MiddlewareGroup)) { + return this.defaultmiddleware[MiddlewareGroup]; + } + return null; }; /* --------------------------------------------------- * Private Functions * --------------------------------------------------- */ Middleware.prototype._loadMiddlewareFile = function (MiddlewareGroup, file) { - var MiddlewareClass = null; + var MiddlewareClass = null; + + try { + MiddlewareClass = require(file); + } catch (err) {} + // this is ok - try { - MiddlewareClass = require(file); - } catch (err) {} - // this is ok + // try loading file as path + if (!MiddlewareClass && fs.existsSync(file)) { + MiddlewareClass = require(file); + } - // try loading file as path - if (!MiddlewareClass && fs.existsSync(file)) { - MiddlewareClass = require(file); + if (MiddlewareClass) { + if (_.isFunction(MiddlewareClass)) { + MiddlewareClass = new MiddlewareClass(); } - if (MiddlewareClass) { - if (_.isFunction(MiddlewareClass)) { - MiddlewareClass = new MiddlewareClass(); - } - - // if getInfo function does not exist auto add wrapper - if (!MiddlewareClass.getInfo) { - if (!MiddlewareGroup) { - logger.warn("Could not determine Middleware Type", file); - return null; - } - - MiddlewareClass.getInfo = function () { - return { - type: MiddlewareGroup, - name: file - }; - }; - } - - return this._setMiddleware(MiddlewareClass); + // if getInfo function does not exist auto add wrapper + if (!MiddlewareClass.getInfo) { + if (!MiddlewareGroup) { + logger.warn('Could not determine Middleware Type', file); + return null; + } + + MiddlewareClass.getInfo = function () { + return { + type: MiddlewareGroup, + name: file + }; + }; } - return null; + return this._setMiddleware(MiddlewareClass); + } + + return null; }; Middleware.prototype._getMiddleware = function (MiddlewareGroup, MiddlewareName) { - if (this.middleware.hasOwnProperty(MiddlewareGroup) && this.middleware[MiddlewareGroup].hasOwnProperty(MiddlewareName)) { - return this.middleware[MiddlewareGroup][MiddlewareName]; - } - return null; + if (this.middleware.hasOwnProperty(MiddlewareGroup) && this.middleware[MiddlewareGroup].hasOwnProperty(MiddlewareName)) { + return this.middleware[MiddlewareGroup][MiddlewareName]; + } + return null; }; Middleware.prototype._setMiddleware = function (MiddlewareClass) { - - var middlewareInstance = null; - var mInfo = { - type: '', - name: '' - }; - if (_.isFunction(MiddlewareClass)) { - middlewareInstance = new MiddlewareClass(); - } else if (_.isObject(MiddlewareClass)) { - middlewareInstance = MiddlewareClass; - } else { - // should not happen - return; + var middlewareInstance = null; + var mInfo = { + type: '', + name: '' + }; + if (_.isFunction(MiddlewareClass)) { + middlewareInstance = new MiddlewareClass(); + } else if (_.isObject(MiddlewareClass)) { + middlewareInstance = MiddlewareClass; + } else { + // should not happen + return; + } + + if (middlewareInstance.getInfo && _.isFunction(middlewareInstance.getInfo)) { + mInfo = middlewareInstance.getInfo(); + } + + if (!(mInfo.type && mInfo.name && _.isString(mInfo.name) && _.isString(mInfo.type))) { + logger.warn('Invalid Middleware Info', mInfo); + } + + // create group/type if not exist + if (!_.isObject(this.middleware[mInfo.type])) { + this.middleware[mInfo.type] = {}; + } + + // check if middle ware exists + // already exists then skip creating + // if above is not used it will be GC'd + if (!_.isObject(this.middleware[mInfo.type][mInfo.name])) { + // create Middleware + this.middleware[mInfo.type][mInfo.name] = middlewareInstance; + + // TODO: remove init in favor or $perStartInit function + if (_.isFunction(this.middleware[mInfo.type][mInfo.name].init)) { + try { + this.middleware[mInfo.type][mInfo.name].init(); + } catch (err) { + logger.error('Loading Middleware Error:', err); + return null; + } } - - if (middlewareInstance.getInfo && _.isFunction(middlewareInstance.getInfo)) { - mInfo = middlewareInstance.getInfo(); + // run $perStartInit function + if (_.isFunction(this.middleware[mInfo.type][mInfo.name].$perStartInit)) { + try { + this.middleware[mInfo.type][mInfo.name].$perStartInit(); + } catch (err) { + logger.error('Loading Middleware Error:', err); + return null; + } } - if (!(mInfo.type && mInfo.name && _.isString(mInfo.name) && _.isString(mInfo.type))) { - logger.warn("Invalid Middleware Info", mInfo); - } + // set it as default + this._setDefault(mInfo.type, mInfo.name); - // create group/type if not exist - if (!_.isObject(this.middleware[mInfo.type])) { - this.middleware[mInfo.type] = {}; - } + logger.log('---------------------------------------------'); + logger.log('Loaded Middleware (' + mInfo.type + ', ' + mInfo.name + ')'); + } - // check if middle ware exists - // already exists then skip creating - // if above is not used it will be GC'd - if (!_.isObject(this.middleware[mInfo.type][mInfo.name])) { - // create Middleware - this.middleware[mInfo.type][mInfo.name] = middlewareInstance; - - // TODO: remove init in favor or $perStartInit function - if (_.isFunction(this.middleware[mInfo.type][mInfo.name].init)) { - try { - this.middleware[mInfo.type][mInfo.name].init(); - } catch (err) { - logger.error("Loading Middleware Error:", err); - return null; - } - } - // run $perStartInit function - if (_.isFunction(this.middleware[mInfo.type][mInfo.name].$perStartInit)) { - try { - this.middleware[mInfo.type][mInfo.name].$perStartInit(); - } catch (err) { - logger.error("Loading Middleware Error:", err); - return null; - } - } - - // set it as default - this._setDefault(mInfo.type, mInfo.name); - - logger.log('---------------------------------------------'); - logger.log("Loaded Middleware (" + mInfo.type + ", " + mInfo.name + ")"); - } - - return this.middleware[mInfo.type][mInfo.name]; + return this.middleware[mInfo.type][mInfo.name]; }; Middleware.prototype._setDefault = function (MiddlewareGroup, MiddlewareName) { - var Middleware = this._getMiddleware(MiddlewareGroup, MiddlewareName); + var Middleware = this._getMiddleware(MiddlewareGroup, MiddlewareName); + + if (Middleware) { + if (!_.isObject(this.defaultmiddleware[MiddlewareGroup])) { + this.defaultmiddleware[MiddlewareGroup] = { + name: null, + Middleware: null + }; + } + + // set default + this.defaultmiddleware[MiddlewareGroup].name = MiddlewareName; + this.defaultmiddleware[MiddlewareGroup].Middleware = Middleware; + return this.defaultmiddleware[MiddlewareGroup]; + } else { + // if Middleware not exist then try to load it + Middleware = this.Middleware(MiddlewareGroup, MiddlewareName); + // if Middleware created, set it to default, as intended if (Middleware) { - if (!_.isObject(this.defaultmiddleware[MiddlewareGroup])) { - this.defaultmiddleware[MiddlewareGroup] = { - name: null, - Middleware: null - }; - } - - // set default - this.defaultmiddleware[MiddlewareGroup].name = MiddlewareName; - this.defaultmiddleware[MiddlewareGroup].Middleware = Middleware; - - return this.defaultmiddleware[MiddlewareGroup]; - } else { - // if Middleware not exist then try to load it - Middleware = this.Middleware(MiddlewareGroup, MiddlewareName); - // if Middleware created, set it to default, as intended - if (Middleware) { - return this._setDefault(MiddlewareGroup, MiddlewareName); - } + return this._setDefault(MiddlewareGroup, MiddlewareName); } + } - return null; + return null; }; \ No newline at end of file diff --git a/legacy/manager.resource.js b/legacy/manager.resource.js new file mode 100644 index 0000000..fdb0992 --- /dev/null +++ b/legacy/manager.resource.js @@ -0,0 +1,201 @@ +'use strict'; + +var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _createClass2 = require('babel-runtime/helpers/createClass'); + +var _createClass3 = _interopRequireDefault(_createClass2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var path = require('path'); +var fs = require('fs'); + +var _ = require('lodash'); +var when = require('when'); + +var ResourceManager = function () { + function ResourceManager(serviceManager, service, logger) { + (0, _classCallCheck3.default)(this, ResourceManager); + + this._serviceManager = serviceManager; + this._service = service; + this._L = logger; + this._resources = {}; + } + + (0, _createClass3.default)(ResourceManager, [{ + key: 'load', + value: function load(resources) { + var pList = []; + + _.forEach(resources, function (resource) { + var p = this.add(resource); + pList.push(p); + }.bind(this)); + + return when.all(pList); + } + }, { + key: 'postStartInit', + value: function postStartInit() { + var pList = []; + + _.forEach(this._resources, function (resource) { + if (resource.instance && _.isFunction(resource.instance.$postStartInit)) { + try { + var result = this._serviceManager.injectionDependency(module, this._service, resource.instance, resource.instance.$postStartInit); + // is promise + if (_.isObject(result) && _.isFunction(result.then)) { + pList.push(result); + } + } catch (err) { + this._L.error('Post Start Init Service Error:', err); + return when.reject(err); + } + } + }.bind(this)); + + return when.all(pList); + } + }, { + key: 'getAllModules', + value: function getAllModules() { + var list = {}; + _.forEach(this._resources, function (resource, name) { + list[name] = resource.module; + }); + return list; + } + }, { + key: 'getAllInstances', + value: function getAllInstances() { + var list = {}; + _.forEach(this._resources, function (resource, name) { + list[name] = resource.instance; + }); + return list; + } + }, { + key: 'add', + value: function add(name, resourceModule) { + var type = arguments.length <= 2 || arguments[2] === undefined ? 'factory' : arguments[2]; + var group = arguments.length <= 3 || arguments[3] === undefined ? 'default' : arguments[3]; + + if (_.isObject(name)) { + var resObj = name; + resourceModule = resObj.module; + type = resObj.type; + group = resObj.group; + name = resObj.name; + } + + var resourceInstance = resourceModule; + var promise = null; + + if (!type) { + type = 'factory'; + } + + if (!_.isString(name)) { + this._L.error("argument1 ('name') needs to be a string"); + } + + if (!resourceModule) { + resourceModule = name; + } + + this._L.log('Adding Resource "%s"', name); + + // if string try to load file + if (_.isString(resourceModule)) { + // load resource from file + resourceModule = this._loadResourceFile(name, resourceModule); + } + + if (type === 'factory') { + if (_.isFunction(resourceModule)) { + var _module = {}; + var InjectedModule = this._serviceManager.injectionDependency(_module, this._service, { + module: resourceModule + }); + resourceInstance = new InjectedModule(); + + // run $init function + if (_.isFunction(resourceInstance.$init)) { + try { + var result = this._serviceManager.injectionDependency(_module, this._service, resourceInstance, resourceInstance.$init); + + // is promise + if (_.isObject(result) && _.isFunction(result.then)) { + promise = result.then(function () { + return resourceInstance; + }); + } + } catch (err) { + this._L.error('Loading Middleware Error:', err); + return when.resolve(null); + } + } + } else { + this._L.error("argument2 ('resource') needs to be a function/module"); + } + } + + if (_.isObject(resourceModule)) { + this._resources[name] = { + module: resourceModule, + instance: resourceInstance + }; + } else { + this._L.info("Could not find or load resource '%s'", name); + } + + if (!promise) { + promise = when.resolve(resourceInstance); + } + + // to support the adding resouce on service constructor + if (this._serviceManager.isLoading()) { + this._serviceManager.addToLoadingQ(this._service, promise); + } + + return promise; + } + }, { + key: '_loadResourceFile', + value: function _loadResourceFile(name, file) { + var tmpFile = path.join(process.cwd(), file); + if (fs.existsSync(tmpFile)) { + try { + return require(tmpFile); + } catch (err) { + // not needed + } + } + + // TODO: is this needed? could be removed + // mod = this._loadFile(type, name, file); + // if (mod) { + // return mod; + // } + // mod = this._loadFile(type, name, '.'); + // if (mod) { + // return mod; + // } + // for (var key in this._services) { + // mod = this._loadFile(type, name, this._services[key].directory.service); + // if (mod) { + // return mod; + // } + // } + + return null; + } + }]); + return ResourceManager; +}(); + +module.exports = ResourceManager; \ No newline at end of file diff --git a/legacy/manager.service.config.js b/legacy/manager.service.config.js index 2b6f7fc..1d93c60 100644 --- a/legacy/manager.service.config.js +++ b/legacy/manager.service.config.js @@ -20,232 +20,231 @@ var util = require('./util.js'); var logger = null; var ServiceManagerConfig = function () { - // var appName = this._config.appName || this._defaultAppName; - function ServiceManagerConfig(appName, config) { - (0, _classCallCheck3.default)(this, ServiceManagerConfig); - - this._appName = appName; - this._config = config; - if (!this._config) { - this._config = {}; - } + // var appName = this._config.appName || this._defaultAppName; + function ServiceManagerConfig(appName, config) { + (0, _classCallCheck3.default)(this, ServiceManagerConfig); + + this._appName = appName; + this._config = config; + if (!this._config) { + this._config = {}; + } + + logger = util.logger('ServicesConfig'); - logger = util.logger('ServicesConfig'); + this._normalize(); + } - this._normalize(); + (0, _createClass3.default)(ServiceManagerConfig, [{ + key: 'get', + value: function get() { + return this._config; } + }, { + key: '_normalize', + value: function _normalize() { + // copy to be applied to _config + var config = this._config; + if (_.isArray(config) || _.isObject(config)) { + config = _.cloneDeep(this._config); + } + + // setup normalized object + this._config = { + services: {} + }; + + // if array + if (_.isArray(config)) { + config.forEach(this._normalizeService.bind(this)); + } else if (_.isObject(config) && config.hasOwnProperty('services')) { + // has sub services + _.forEach(config.services, function (service, key) { + if (!service.hasOwnProperty('name')) { + service.name = key; + } + + this._normalizeService(service); + }.bind(this)); + } + // if string or object + else if (_.isString(config) || _.isObject(config)) { + this._normalizeService(config); + } else { + logger.error('Invalid config type:', config); + } - (0, _createClass3.default)(ServiceManagerConfig, [{ - key: 'get', - value: function get() { - return this._config; + // TODO: add to verbose + // logger.info("normalize service config:", JSON.stringify(this._config, null, 2)); + } + }, { + key: '_normalizeService', + value: function _normalizeService(service) { + var key = this._appName; + var defaultService = { + config: {}, + options: {}, + preRoutes: {}, + routes: [], + directory: { service: 'lib', controllers: '', resolvers: '', views: '', static: '' } + }; + + // ----------------------------------------------- + if (_.isString(service)) { + key = service; + service = defaultService; + // + service.name = key; + service.directory.service = key; + } else if (_.isObject(service)) { + if (service.hasOwnProperty('name')) { + key = service.name; + defaultService.directory.service = service.name; + } else { + service.name = key; } - }, { - key: '_normalize', - value: function _normalize() { - // copy to be applied to _config - var config = this._config; - if (_.isArray(config) || _.isObject(config)) { - config = _.cloneDeep(this._config); - } - // setup normalized object - this._config = { - services: {} - }; - - // if array - if (_.isArray(config)) { - config.forEach(this._normalizeService.bind(this)); - } else if (_.isObject(config) && config.hasOwnProperty('services')) { - // has sub services - _.forEach(config.services, function (service, key) { - if (!service.hasOwnProperty('name')) { - service.name = key; - } - - this._normalizeService(service); - }.bind(this)); - } - // if string or object - else if (_.isString(config) || _.isObject(config)) { - this._normalizeService(config); - } else { - logger.error('Invalid config type:', config); - } - - // TODO: add to verbose - // logger.info("normalize service config:", JSON.stringify(this._config, null, 2)); + if (service.hasOwnProperty('directory') && _.isString(service.directory)) { + defaultService.directory.service = service.directory; + service.directory = defaultService.directory; } - }, { - key: '_normalizeService', - value: function _normalizeService(service) { - var key = this._appName; - var defaultService = { - config: {}, - options: {}, - preRoutes: {}, - routes: [], - directory: { service: "lib", controllers: "", resolvers: "", views: "", static: "" } - }; - - // ----------------------------------------------- - if (_.isString(service)) { - key = service; - service = defaultService; - // - service.name = key; - service.directory.service = key; - } else if (_.isObject(service)) { - if (service.hasOwnProperty('name')) { - key = service.name; - defaultService.directory.service = service.name; - } else { - service.name = key; - } - - if (service.hasOwnProperty('directory') && _.isString(service.directory)) { - defaultService.directory.service = service.directory; - service.directory = defaultService.directory; - } - - service = _.merge(defaultService, service); - } else { - logger.warn('Invalid service type:', service); - } - // ----------------------------------------------- - - // check if service.directories exists - // find dir for each type - _.forEach(service.directory, function (dir, d) { - //logger.info("d:", d, ", key:", key, ", directory:", service.directory[d], ", directory.service:", service.directory.service); - service.directory[d] = this._findDir(d, service.directory[d], key, service.directory.service); - //logger.info("found directory:", service.directory[d]); - - if (!service.directory[d]) { - logger.info("Could not find " + d + " dir in App dir (" + process.cwd() + ")"); - //service.directory[d] = service.name; - // if not, set to current working dir - service.directory[d] = process.cwd(); - } - }.bind(this)); - - // ---------------------------------------- - // TODO: load controllers first - // ---------------------------------------- - - - // if config does not contain routes - // try to load a routes file using app name - if (!service.hasOwnProperty('routes') || !(_.isArray(service.routes) && service.routes.length)) { - try { - // use directory as root to look for routes file - var fileSearchPath = path.resolve(process.cwd(), service.directory.service) + path.sep + '**' + path.sep + service.name + '.routes.js'; - //logger.log("fileSearchPath:", fileSearchPath); - var globs = glob.sync(fileSearchPath); - //logger.log("globs list:", globs); - - // remove all node_modules - globs = util.filterNodeModules(globs); - //logger.log("globs after filter:", globs); - - if (globs.length === 0) { - logger.info("Could not find a routes files and service defined (%s)", fileSearchPath); - } - // TODO: also check the controllers didn't have routes defined - else if (globs.length > 1) { - logger.warn("More than one route file found", globs); - } - - if (globs.length === 1) { - var file = path.resolve(globs[0]); - service.routes = require(file); - } - } catch (err) { - logger.warn("Could not load routes files.", err); - return; - } - } - // ----------------------------------------------- - if (this._config.services.hasOwnProperty(key)) { - logger.warn('Service already in services:', key); + service = _.merge(defaultService, service); + } else { + logger.warn('Invalid service type:', service); + } + // ----------------------------------------------- + + // check if service.directories exists + // find dir for each type + _.forEach(service.directory, function (dir, d) { + // logger.info("d:", d, ", key:", key, ", directory:", service.directory[d], ", directory.service:", service.directory.service); + service.directory[d] = this._findDir(d, service.directory[d], key, service.directory.service); + // logger.info("found directory:", service.directory[d]); + + if (!service.directory[d]) { + logger.info('Could not find ' + d + ' dir in App dir (' + process.cwd() + ')'); + // service.directory[d] = service.name; + // if not, set to current working dir + service.directory[d] = process.cwd(); + } + }.bind(this)); + + // ---------------------------------------- + // TODO: load controllers first + // ---------------------------------------- + + // if config does not contain routes + // try to load a routes file using app name + if (!service.hasOwnProperty('routes') || !(_.isArray(service.routes) && service.routes.length)) { + try { + // use directory as root to look for routes file + var fileSearchPath = path.resolve(process.cwd(), service.directory.service) + path.sep + '**' + path.sep + service.name + '.routes.js'; + // logger.log("fileSearchPath:", fileSearchPath); + var globs = glob.sync(fileSearchPath); + // logger.log("globs list:", globs); + + // remove all node_modules + globs = util.filterNodeModules(globs); + // logger.log("globs after filter:", globs); + + if (globs.length === 0) { + logger.info('Could not find a routes files and service defined (%s)', fileSearchPath); + } + // TODO: also check the controllers didn't have routes defined + else if (globs.length > 1) { + logger.warn('More than one route file found', globs); } - //logger.log("normalize service:", JSON.stringify(service, null, 2)); - this._config.services[key] = service; + if (globs.length === 1) { + var file = path.resolve(globs[0]); + service.routes = require(file); + } + } catch (err) { + logger.warn('Could not load routes files.', err); + return; } + } - // directory default: "lib/" - - }, { - key: '_findDir', - value: function _findDir(type, configDirectory, serviceName, serviceDir) { - // check if configDir is set, a string and not empty - if (configDirectory && _.isString(configDirectory) && configDirectory.length > 0) { - // add cwd, if need be - configDirectory = path.resolve(configDirectory); - if (fs.existsSync(configDirectory)) { - return configDirectory; - } - } + // ----------------------------------------------- + if (this._config.services.hasOwnProperty(key)) { + logger.warn('Service already in services:', key); + } - // find it - var file = ""; - var globs = null; - if (type === "service") { - // look for service/app file - file = path.sep + "service." + serviceName + ".js"; - globs = glob.sync('**' + file); - - // remove all node_modules - globs = util.filterNodeModules(globs); - - // check if file exists - if (globs.length > 0) { - if (globs.length > 1) { - logger.warn("More than one service file found", globs); - } - // dirname removes files from results - return path.dirname(process.cwd() + path.sep + globs[0]); - } - - file = path.sep + serviceName + ".js"; - globs = glob.sync('**' + file); - // remove all node_modules - globs = util.filterNodeModules(globs); - - // check if file exists - if (globs.length > 0) { - if (globs.length > 1) { - logger.warn("More than one service file found", globs); - } - // dirname removes files from results - return path.dirname(process.cwd() + path.sep + globs[0]); - } - - // default "//lib" - return process.cwd() + path.sep + "lib"; - } else { - // start in service dir - globs = glob.sync(serviceDir + path.sep + '**' + path.sep + type); - // remove all node_modules - globs = util.filterNodeModules(globs); - - // check if file exists - if (globs.length > 0) { - if (globs.length > 1) { - logger.warn("More than one service file found", globs); - } - return globs[0]; - } - - // default "/" - return serviceDir + path.sep + type; - } + // logger.log("normalize service:", JSON.stringify(service, null, 2)); + this._config.services[key] = service; + } + + // directory default: "lib/" + + }, { + key: '_findDir', + value: function _findDir(type, configDirectory, serviceName, serviceDir) { + // check if configDir is set, a string and not empty + if (configDirectory && _.isString(configDirectory) && configDirectory.length > 0) { + // add cwd, if need be + configDirectory = path.resolve(configDirectory); + if (fs.existsSync(configDirectory)) { + return configDirectory; + } + } + + // find it + var file = ''; + var globs = null; + if (type === 'service') { + // look for service/app file + file = path.sep + 'service.' + serviceName + '.js'; + globs = glob.sync('**' + file); + + // remove all node_modules + globs = util.filterNodeModules(globs); + + // check if file exists + if (globs.length > 0) { + if (globs.length > 1) { + logger.warn('More than one service file found', globs); + } + // dirname removes files from results + return path.dirname(process.cwd() + path.sep + globs[0]); + } + + file = path.sep + serviceName + '.js'; + globs = glob.sync('**' + file); + // remove all node_modules + globs = util.filterNodeModules(globs); + + // check if file exists + if (globs.length > 0) { + if (globs.length > 1) { + logger.warn('More than one service file found', globs); + } + // dirname removes files from results + return path.dirname(process.cwd() + path.sep + globs[0]); + } + + // default "//lib" + return process.cwd() + path.sep + 'lib'; + } else { + // start in service dir + globs = glob.sync(serviceDir + path.sep + '**' + path.sep + type); + // remove all node_modules + globs = util.filterNodeModules(globs); + + // check if file exists + if (globs.length > 0) { + if (globs.length > 1) { + logger.warn('More than one service file found', globs); + } + return globs[0]; } - }]); - return ServiceManagerConfig; + + // default "/" + return serviceDir + path.sep + type; + } + } + }]); + return ServiceManagerConfig; }(); module.exports = ServiceManagerConfig; \ No newline at end of file diff --git a/legacy/manager.service.js b/legacy/manager.service.js index 5e4bd6b..b0ebfdc 100644 --- a/legacy/manager.service.js +++ b/legacy/manager.service.js @@ -13,18 +13,9 @@ var _stringify = require('babel-runtime/core-js/json/stringify'); var _stringify2 = _interopRequireDefault(_stringify); -var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _createClass2 = require('babel-runtime/helpers/createClass'); - -var _createClass3 = _interopRequireDefault(_createClass2); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var fs = require('fs'); -var http = require('http'); var path = require('path'); // var _ = require('lodash'); @@ -38,7 +29,7 @@ var defaultAppService = require('./default.service.app.js'); // var ServiceManagerConfig = require('./manager.service.config.js'); // Normalize Service Configs var ServiceRouter = require('./router.service.js'); -var ResourceHandler = require('./handler.resource.js'); +var ResourceManager = require('./manager.resource.js'); var logger = null; @@ -47,499 +38,359 @@ module.exports = ServiceManager; /** --------------------------------------------------- * Public Functions * --------------------------------------------------- */ - -var Service = function () { - function Service() { - (0, _classCallCheck3.default)(this, Service); - } - - (0, _createClass3.default)(Service, [{ - key: 'init', - - /** - * initialize service - */ - value: function init() {} - // TODO - - - /** - * load service routes into http framework - */ - - }, { - key: 'load', - value: function load() {} - // TODO - - - /** - * adds route to http framework - * @param routeConfig - */ - - }, { - key: 'addRoute', - value: function addRoute(routeConfig) {} - // TODO - - - /** - * adds resource to service - * @param resourceConfig - */ - - }, { - key: 'addResource', - value: function addResource(resourceConfig) { - // TODO - } - }]); - return Service; -}(); - -var _ServiceManager = function () { - function _ServiceManager() { - (0, _classCallCheck3.default)(this, _ServiceManager); - } - - (0, _createClass3.default)(_ServiceManager, [{ - key: 'init', - - /** - * initialize services - * load config - * normalize service configs - * check files exist - * any prep before loading the service into the http framework - */ - value: function init() {} - // TODO - - // load service plugins - // - dynamic (api) - // - template (view) - // - static - // - redirect - // - otherwise - // - auth - // - ... - - - /** - * load services routes into http framework - * mostly a config to -> addService helper - */ - - }, { - key: 'load', - value: function load() {} - // TODO - - - /** - * adds a service to the manager - * adds all routes defined in the config to http framework - * @param serviceConfig - * @returns Service Object - */ - - }, { - key: 'add', - value: function add(serviceConfig) {} - // TODO - - - /** - * get Service Object from serviceId - * @param serviceId - * @returns Service Object - */ - - }, { - key: 'get', - value: function get(serviceId) { - // TODO - } - }]); - return _ServiceManager; -}(); +// class Service { +// /** +// * initialize service +// */ +// init () { +// // TODO +// } + +// /** +// * load service routes into http framework +// */ +// load () { +// // TODO +// } + +// /** +// * adds route to http framework +// * @param routeConfig +// */ +// addRoute (routeConfig) { +// // TODO +// } +// } + +// class _ServiceManager { +// /** +// * initialize services +// * load config +// * normalize service configs +// * check files exist +// * any prep before loading the service into the http framework +// */ +// init () { +// // TODO + +// // load service plugins +// // - dynamic (api) +// // - template (view) +// // - static +// // - redirect +// // - otherwise +// // - auth +// // - ... +// } + +// /** +// * load services routes into http framework +// * mostly a config to -> addService helper +// */ +// load () { +// // TODO +// } + +// /** +// * adds a service to the manager +// * adds all routes defined in the config to http framework +// * @param serviceConfig +// * @returns Service Object +// */ +// add (serviceConfig) { +// // TODO +// } + +// /** +// * get Service Object from serviceId +// * @param serviceId +// * @returns Service Object +// */ +// get (serviceId) { +// // TODO +// } +// } /* --------------------------------------------------- * Constructor * --------------------------------------------------- */ - - function ServiceManager(hyperCore, appConfig, servicesManifest, middleware, serviceMiddlewareManager, httpFramework, defaultAppName) { - - var serviceManagerConfig = appConfig.serviceManager; - this._displayDebuggerInfo = serviceManagerConfig.displayDebuggerInfo; - this._hyperCore = hyperCore; - // TODO: remove this after DI in it's own lib - this._httpFramework = httpFramework; - - // Init Service Router - this._serviceRouter = new ServiceRouter({ - port: this._httpFramework.port(), - protocol: this._httpFramework.protocol() - }); - - // TODO: add statsD to middleware as plugin - //this.stats = new util.Stats(this.options, "ServiceManager"); - logger = util.logger('Services'); - - var manifest = new ServiceManagerConfig(defaultAppName, servicesManifest); // normalizes the configs - this._servicesManifest = manifest.get(); - this._servicesManifest.shared = appConfig.shared; - - var servicesConfigs = {}; - _.forEach(this._servicesManifest.services, function (service, key) { - service.config = _.merge(service.config, appConfig[key] || {}); - servicesConfigs[key] = service.config; - }); - this._serviceRouter.config(servicesConfigs); - - this._services = {}; - this._resources = {}; - - this._serviceMiddlewareManager = serviceMiddlewareManager; - this._serviceMiddlewareManager.init(logger, httpFramework, middleware, this); - //this._serviceMiddlewareManager = new ServiceMiddlewareManager(logger, httpFramework, middleware, this); - //this._serviceMiddlewareManager.add('defaultRoutes'); - //this._serviceMiddlewareManager.add('apiviewRoutes'); + var serviceManagerConfig = appConfig.serviceManager; + this._displayDebuggerInfo = serviceManagerConfig.displayDebuggerInfo; + this._hyperCore = hyperCore; + // TODO: remove this after DI in it's own lib + this._httpFramework = httpFramework; + + // Init Service Router + this._serviceRouter = new ServiceRouter({ + port: this._httpFramework.port(), + protocol: this._httpFramework.protocol() + }); + + // TODO: add statsD to middleware as plugin + // this.stats = new util.Stats(this.options, "ServiceManager"); + logger = util.logger('Services'); + + var manifest = new ServiceManagerConfig(defaultAppName, servicesManifest); // normalizes the configs + this._servicesManifest = manifest.get(); + this._servicesManifest.shared = appConfig.shared; + + var servicesConfigs = {}; + _.forEach(this._servicesManifest.services, function (service, key) { + service.config = _.merge(service.config, appConfig[key] || {}); + servicesConfigs[key] = service.config; + }); + this._serviceRouter.config(servicesConfigs); + + this._services = {}; + // all service wide resoueces + // TODO: remove this in next major version + this._resources = new ResourceManager(this, null, logger); + + this._loading = false; + + this._serviceMiddlewareManager = serviceMiddlewareManager; + this._serviceMiddlewareManager.init(logger, httpFramework, middleware, this); + // this._serviceMiddlewareManager = new ServiceMiddlewareManager(logger, httpFramework, middleware, this); + // this._serviceMiddlewareManager.add('defaultRoutes'); + // this._serviceMiddlewareManager.add('apiviewRoutes'); } /* --------------------------------------------------- * Public Functions * --------------------------------------------------- */ ServiceManager.prototype.getServiceRouter = function () { - return this._serviceRouter; + return this._serviceRouter; }; // load all services ServiceManager.prototype.loadHttpFramework = function () { - return this._httpFramework.load(); + return this._httpFramework.load(); }; // load all services ServiceManager.prototype.loadServices = function () { - return this._loadServices(); + this._loading = true; + return this._loadServices().then(function (result) { + this._loading = false; + return result; + }.bind(this)); }; -ServiceManager.prototype._loadServices = function () { - - logger.log('---------------------------------------------'); - logger.group("Loading Services..."); - - var serviceList = _.values(this._servicesManifest.services); - serviceList.reverse(); - serviceList.push({}); - - return when.reduceRight(serviceList, function (notUsed, serviceManifest, index) { - var service = this._services[serviceManifest.name] = {}; - - service.name = serviceManifest.name; - service.config = serviceManifest.config || {}; - service.options = serviceManifest.options || {}; - service.module = serviceManifest.module || {}; - service.routes = serviceManifest.routes || {}; - service.preRoutes = serviceManifest.preRoutes || {}; - service.controller = serviceManifest.controller || {}; - service.directory = serviceManifest.directory || { - service: "", - controllers: "", - resolvers: "", - views: "", - static: "" - }; - service.resolver = {}; - service.resources = {}; - - service._promiseQueue = []; - - // add service to service router - this._serviceRouter.add(service.name); - - // module default: ".//.js" - if (!serviceManifest.module) { - service.module = this._loadServiceFile(service.name, service.directory.service); +ServiceManager.prototype.isLoading = function () { + return this._loading; +}; - if (!service.module || !_.isFunction(service.module)) { - // use default - service.module = defaultAppService; - } - } +ServiceManager.prototype.addToLoadingQ = function (service, promise) { + service._promiseQueue.push(promise); +}; - // create instance of module - if (service.module) { - logger.group("Loading Service " + service.name + "..."); - - var module = { - '$resource': ['value', this._getResourceHandler(service)], - '$logger': ['value', util.logger(service.name)] - }; - - if (service && service.hasOwnProperty('options')) { - module.$options = ['value', service.options]; - } - - var InjectedModule = this._injectionDependency(module, service, service); - service.instance = new InjectedModule(); - - if (_.isFunction(service.instance.$init)) { - logger.info("Initializing..."); - try { - var result = this._injectionDependency(module, service, service.instance, service.instance.$init); - - // is promise - if (_.isObject(result) && _.isFunction(result.then)) { - service._promiseQueue.push(result); - } - } catch (err) { - logger.error("Initializing Service Error:", err); - return when.reject(err); - } - } - - // create instance of module - if (service.module && service.preRoutes && _.isFunction(service.preRoutes)) { - logger.group("Loading PreRoutes..."); - // DI invoke preRoutes - this._injectionDependency({}, service, service, service.preRoutes); - logger.groupEnd(" "); - } - - var p; - if (service.module) { - logger.group("Loading Setup Routes..."); - // setup service routes - p = this._setupRoutes(service); - service._promiseQueue.push(p); - logger.groupEnd(" "); - } - - if (serviceManifest.resources) { - _.forEach(serviceManifest.resources, function (resourceModule, name) { - this.addResource(name, resourceModule, 'factory', service); - }.bind(this)); - } - - // wait for Q'd resources to resolve before letting service resolve - if (service._promiseQueue.length) { - //logger.info("Wait for Setup..."); - - // TODO: need timeout in case resource promise never resolves - return when.all(service._promiseQueue).then(function () { - delete service._promiseQueue; - //logger.info("Route Setup Complete"); - logger.groupEnd(" "); - }.bind(this)); - } else { - logger.groupEnd(" "); - - return 1; - } - } +ServiceManager.prototype._loadServices = function () { + logger.log('---------------------------------------------'); + logger.group('Loading Services...'); + + var serviceList = _.values(this._servicesManifest.services); + serviceList.reverse(); + serviceList.push({}); + + return when.reduceRight(serviceList, function (notUsed, serviceManifest, index) { + var service = this._services[serviceManifest.name] = { + name: serviceManifest.name, + config: serviceManifest.config || {}, + options: serviceManifest.options || {}, + module: serviceManifest.module || {}, + routes: serviceManifest.routes || {}, + preRoutes: serviceManifest.preRoutes || {}, + controller: serviceManifest.controller || {}, + directory: serviceManifest.directory || { + service: '', + controllers: '', + resolvers: '', + views: '', + static: '' + }, + resolver: {} + }; + service._promiseQueue = []; - if (this._displayDebuggerInfo) { - logger.info('services["%s"]: %s', key, (0, _stringify2.default)(service, null, 2)); - } - }.bind(this)); -}; + service.resources = new ResourceManager(this, service, logger); -// run all post start init on services -ServiceManager.prototype.postStartInit = function () { + // add service to service router + this._serviceRouter.add(service.name); - var serviceList = _.values(this._services); - serviceList.reverse(); - serviceList.push({}); + // module default: ".//.js" + if (!serviceManifest.module) { + service.module = this._loadServiceFile(service.name, service.directory.service); - return when.reduceRight(serviceList, function (notUsed, service) { - logger.group("Running Service " + service.name + " Post Start Init..."); + if (!service.module || !_.isFunction(service.module)) { + // use default + service.module = defaultAppService; + } + } - service._promiseQueue = []; + // create instance of module + if (service.module) { + logger.group('Loading Service ' + service.name + '...'); - if (service.instance && _.isFunction(service.instance.$postStartInit)) { - try { - var result = this._injectionDependency(module, service, service.instance, service.instance.$postStartInit); + var module = { + '$resource': ['value', service.resources], + '$logger': ['value', util.logger(service.name)] + }; - // is promise - if (_.isObject(result) && _.isFunction(service._promiseQueue.then)) { - service._promiseQueue.push(result); - } - } catch (err) { - logger.error("Post Start Init Service Error:", err); - return when.reject(err); - } - } + if (service && service.hasOwnProperty('options')) { + module.$options = ['value', service.options]; + } - _.forEach(service.resources, function (resource) { - if (resource.instance && _.isFunction(resource.instance.$postStartInit)) { - try { - var result = this._injectionDependency(module, service, resource.instance, resource.instance.$postStartInit); - - // is promise - if (_.isObject(result) && _.isFunction(result.then)) { - service._promiseQueue.push(result); - } - } catch (err) { - logger.error("Post Start Init Service Error:", err); - return when.reject(err); - } - } - }.bind(this)); - - // wait for Q'd resources to resolve before letting service resolve - if (service._promiseQueue.length) { - logger.info("Wait Post Start Init..."); - - // TODO: need timeout in case resource promise never resolves - return when.all(service._promiseQueue).then(function () { - delete service._promiseQueue; - - logger.info("Loaded"); - logger.groupEnd(" "); - }.bind(this)); - } else { - logger.groupEnd(" "); + var InjectedModule = this.injectionDependency(module, service, service); + service.instance = new InjectedModule(); - return 1; + if (_.isFunction(service.instance.$init)) { + logger.info('Initializing...'); + try { + var result = this.injectionDependency(module, service, service.instance, service.instance.$init); + + // is promise + if (_.isObject(result) && _.isFunction(result.then)) { + service._promiseQueue.push(result); + } + } catch (err) { + logger.error('Initializing Service Error:', err); + return when.reject(err); } - }.bind(this)); -}; - -ServiceManager.prototype.addResource = function (name, resourceModule, type, service) { - if (!type) { - type = 'factory'; + } + + // create instance of module + if (service.module && service.preRoutes && _.isFunction(service.preRoutes)) { + logger.group('Loading PreRoutes...'); + // DI invoke preRoutes + this.injectionDependency({}, service, service, service.preRoutes); + logger.groupEnd(' '); + } + + var p; + if (service.module) { + logger.group('Loading Setup Routes...'); + // setup service routes + p = this._setupRoutes(service); + service._promiseQueue.push(p); + logger.groupEnd(' '); + } + + if (serviceManifest.resources) { + p = service.resources.load(serviceManifest.resources); + service._promiseQueue.push(p); + } + + // wait for Q'd resources to resolve before letting service resolve + if (service._promiseQueue.length) { + // logger.info("Wait for Setup..."); + + // TODO: need timeout in case resource promise never resolves + return when.all(service._promiseQueue).then(function () { + delete service._promiseQueue; + // logger.info("Route Setup Complete"); + logger.groupEnd(' '); + }); + } else { + logger.groupEnd(' '); + return 1; + } } - if (!_.isString(name)) { - logger.error("argument1 ('name') needs to be a string"); + if (this._displayDebuggerInfo) { + logger.info('services["%s"]: %s', serviceManifest.name, (0, _stringify2.default)(service, null, 2)); } + }.bind(this)); +}; - if (!resourceModule) { - resourceModule = name; - } +ServiceManager.prototype.addResource = function () { + var _resources; - logger.log('Adding Resource "%s"', name); + // find service + return (_resources = this._resources).add.apply(_resources, arguments); +}; - // if string try to load file - if (_.isString(resourceModule)) { - // load resource from file - resourceModule = this._loadResourceFile(name, resourceModule); - } +// run all post start init on services +ServiceManager.prototype.postStartInit = function () { + var serviceList = _.values(this._services); + serviceList.reverse(); + serviceList.push({}); - if (type == 'factory') { - if (_.isFunction(resourceModule)) { - - var module = {}; - var InjectedModule = this._injectionDependency(module, service, { - module: resourceModule - }); - resourceModule = new InjectedModule(); - - // run $init function - if (_.isFunction(resourceModule.$init)) { - try { - var result = this._injectionDependency(module, service, resourceModule, resourceModule.$init); - - // is promise - if (_.isObject(result) && _.isFunction(result.then)) { - service._promiseQueue.push(result); - } - } catch (err) { - logger.error("Loading Middleware Error:", err); - return null; - } - } - } else { - logger.error("argument2 ('resource') needs to be a function/module"); - } - } + return when.reduceRight(serviceList, function (notUsed, service) { + var result = null; + logger.group('Running Service ' + service.name + ' Post Start Init...'); - if (_.isObject(resourceModule)) { + service._promiseQueue = []; - if (!service) { - this._resources[name] = { - module: resourceModule, - instance: resourceModule - }; - } else { - service.resources[name] = { - module: resourceModule, - instance: resourceModule - }; + if (service.instance && _.isFunction(service.instance.$postStartInit)) { + try { + result = this.injectionDependency(module, service, service.instance, service.instance.$postStartInit); + + // is promise + if (_.isObject(result) && _.isFunction(service._promiseQueue.then)) { + service._promiseQueue.push(result); } - } else { - logger.info("Could not find or load resource '%s'", name); + } catch (err) { + logger.error('Post Start Init Service Error:', err); + return when.reject(err); + } } - return resourceModule; -}; + // + result = service.resources.postStartInit(); + service._promiseQueue.push(result); -ServiceManager.prototype._getResourceHandler = function (service) { - return new ResourceHandler(this, service); -}; + // wait for Q'd resources to resolve before letting service resolve + if (service._promiseQueue.length) { + logger.info('Wait Post Start Init...'); -ServiceManager.prototype._loadResourceFile = function (name, file) { - var mod = null; - var type = 'resource'; + // TODO: need timeout in case resource promise never resolves + return when.all(service._promiseQueue).then(function () { + delete service._promiseQueue; - var tmpFile = path.join(process.cwd(), file); - if (fs.existsSync(tmpFile)) { - try { - return require(tmpFile); - } catch (err) {} - } - - mod = this._loadFile(type, name, file); - if (mod) { - return mod; - } - - mod = this._loadFile(type, name, '.'); - if (mod) { - return mod; - } + logger.info('Loaded'); + logger.groupEnd(' '); + }); + } else { + logger.groupEnd(' '); - for (var key in this._services) { - mod = this._loadFile(type, name, this._services[key].directory.service); - if (mod) { - return mod; - } + return 1; } - - return null; + }.bind(this)); }; ServiceManager.prototype._loadFile = function (type, key, directory) { - var file = ""; - + var file = ''; + + // try to loading service file + file = directory + path.sep + key + '.js'; + file = path.join(process.cwd(), file); + // logger.info('Trying to load:', file); + + // check if file exists + if (fs.existsSync(file)) { + try { + return require(file); + } catch (err) { + // this is ok + } + } else { // try to loading service file - file = directory + path.sep + key + ".js"; + file = directory + path.sep + type + '.' + key + '.js'; file = path.join(process.cwd(), file); - //logger.info('Trying to load:', file); + // logger.info('Trying to load:', file); // check if file exists if (fs.existsSync(file)) { - try { - return require(file); - } catch (err) {} - } else { - // try to loading service file - file = directory + path.sep + type + "." + key + ".js"; - file = path.join(process.cwd(), file); - //logger.info('Trying to load:', file); - - // check if file exists - if (fs.existsSync(file)) { - try { - return require(file); - } catch (err) {} - } + try { + return require(file); + } catch (err) { + // this is ok + } } + } - return null; + return null; }; /* --------------------------------------------------- @@ -547,144 +398,144 @@ ServiceManager.prototype._loadFile = function (type, key, directory) { * --------------------------------------------------- */ ServiceManager.prototype._setupRoutes = function (service) { - return when.reduce(service.routes, function (notUsed, route) { - - // return controller created or from cache - var controller = this._setupController(service, route); - if (this._displayDebuggerInfo) { - logger.info("Controller:", (0, _stringify2.default)(controller, null, 2)); - } + return when.reduce(service.routes, function (notUsed, route) { + // return controller created or from cache + var controller = this._setupController(service, route); + if (this._displayDebuggerInfo) { + logger.info('Controller:', (0, _stringify2.default)(controller, null, 2)); + } - // Setup Resolver, if they exist - route.resolve = this._setupResolver(service, route); + // Setup Resolver, if they exist + route.resolve = this._setupResolver(service, route); - // switch based on the properties - var p = null; - if (this._serviceMiddlewareManager.hasHandler(route)) { - p = this._serviceMiddlewareManager.setup(service, controller, route); - } else { - logger.warn("Service \"" + service.name + "\" has invalid route", route); - } + // switch based on the properties + var p = null; + if (this._serviceMiddlewareManager.hasHandler(route)) { + p = this._serviceMiddlewareManager.setup(service, controller, route); + } else { + logger.warn('Service "' + service.name + '" has invalid route', route); + } - // if 'p' null then return resolved promise - return p || when.resolve(); - }.bind(this), 0); + // if 'p' null then return resolved promise + return p || when.resolve(); + }.bind(this), 0); }; +// TODO: move this to it's own class ServiceManager.prototype._setupController = function (service, route) { - var controller; - var controllerName = service.name; - - // no controller, this is ok - // create default controller - if (!route.controller) { - if (this._displayDebuggerInfo) { - logger.info("Controller missing for", service.name); - } + var controller; + var controllerName = service.name; + + // no controller, this is ok + // create default controller + if (!route.controller) { + if (this._displayDebuggerInfo) { + logger.info('Controller missing for', service.name); + } - service.controller[controllerName] = { - name: controllerName, - config: service.config, - module: function module() {}, - instance: function instance() {} - }; - service.controller[controllerName].instance.config = service.config; + service.controller[controllerName] = { + name: controllerName, + config: service.config, + module: function module() {}, + instance: function instance() {} + }; + service.controller[controllerName].instance.config = service.config; - return service.controller[controllerName]; - } else if (_.isString(route.controller)) { - controllerName = route.controller; - } else if (_.isObject(route.controller) && route.controller.hasOwnProperty('name')) { - controllerName = route.controller.name; + return service.controller[controllerName]; + } else if (_.isString(route.controller)) { + controllerName = route.controller; + } else if (_.isObject(route.controller) && route.controller.hasOwnProperty('name')) { + controllerName = route.controller.name; + } + + if (service.controller[controllerName]) { + if (service.controller[controllerName].instance) { + // controller already loaded + return service.controller[controllerName]; } - - if (service.controller[controllerName]) { - if (service.controller[controllerName].instance) { - // controller already loaded - return service.controller[controllerName]; + } else { + // create one, required data should be filled in the section below + service.controller[controllerName] = {}; + } + + logger.info('Loading Controller:', controllerName); + // if no controller loaded already + if (_.keys(service.controller[controllerName]).length === 0) { + if (_.isString(route.controller)) { + // try to load controller as file + var file = route.controller; + controller = null; + if (fs.existsSync(file)) { + try { + controller = require(file); + } catch (err) { + logger.error('Loading Service "' + service.name + '" controller (' + route.controller + ') Error:', err); } - } else { - // create one, required data should be filled in the section below - service.controller[controllerName] = {}; - } + } - logger.info("Loading Controller:", controllerName); - // if no controller loaded already - if (_.keys(service.controller[controllerName]).length === 0) { - if (_.isString(route.controller)) { - // try to load controller as file - var file = route.controller; - controller = null; - if (fs.existsSync(file)) { - try { - controller = require(file); - } catch (err) { - logger.error("Loading Service \"" + service.name + "\" controller (" + route.controller + ") Error:", err); - } - } - - if (!controller) { - // controller default: "/controllers/.js" - file = path.normalize(service.directory.controllers + path.sep + route.controller + ".js"); - //logger.log("setupController file:", file); - if (fs.existsSync(file)) { - // need to add the current cwd because require is relative to this file - try { - controller = require(file); - } catch (err) { - logger.error("Loading Service \"" + service.name + "\" controller (" + route.controller + ") Error:", err); - } - } - } - - if (!controller) { - // error - logger.warn("Service \"" + service.name + "\" controller (" + route.controller + ") invalid"); - return; - } else { - service.controller[controllerName].module = controller; - logger.info("Loaded Controller:", controllerName); - } - } else if (_.isObject(route.controller)) { - if (route.controller.hasOwnProperty('module') && route.controller.hasOwnProperty('instance')) { - service.controller[controllerName] = route.controller; - } else { - service.controller[controllerName].module = route.controller; - } - } else { - // error - logger.warn("Service \"" + service.name + "\" controller (" + route.controller + ") invalid"); - return; + if (!controller) { + // controller default: "/controllers/.js" + file = path.normalize(service.directory.controllers + path.sep + route.controller + '.js'); + // logger.log("setupController file:", file); + if (fs.existsSync(file)) { + // need to add the current cwd because require is relative to this file + try { + controller = require(file); + } catch (err) { + logger.error('Loading Service "' + service.name + '" controller (' + route.controller + ') Error:', err); + } } - } - - // if controller does not have a config then pass service along - if (!service.controller[controllerName].hasOwnProperty('config')) { - service.controller[controllerName].config = service.config; - } + } - // make sure controller has name - if (!service.controller[controllerName].name) { - service.controller[controllerName].name = controllerName; + if (!controller) { + // error + logger.warn('Service "' + service.name + '" controller (' + route.controller + ') invalid'); + return; + } else { + service.controller[controllerName].module = controller; + logger.info('Loaded Controller:', controllerName); + } + } else if (_.isObject(route.controller)) { + if (route.controller.hasOwnProperty('module') && route.controller.hasOwnProperty('instance')) { + service.controller[controllerName] = route.controller; + } else { + service.controller[controllerName].module = route.controller; + } + } else { + // error + logger.warn('Service "' + service.name + '" controller (' + route.controller + ') invalid'); + return; } - - if (service.controller[controllerName].instance === null || service.controller[controllerName].instance === undefined) { - if (_.isFunction(service.controller[controllerName].module)) { - var module = { - '$service': ['value', service.instance], - '$options': ['value', service.options[controllerName]], - '$logger': ['value', util.logger(service.name + ' - ' + controllerName)] // TODO: add logger to controller object - }; - - var InjectedModule = this._injectionDependency(module, service, service.controller[controllerName]); - - service.controller[controllerName].instance = new InjectedModule(); - //service.controller[controllerName].instance = new controller(); - } else { - service.controller[controllerName].instance = controller; - } + } + + // if controller does not have a config then pass service along + if (!service.controller[controllerName].hasOwnProperty('config')) { + service.controller[controllerName].config = service.config; + } + + // make sure controller has name + if (!service.controller[controllerName].name) { + service.controller[controllerName].name = controllerName; + } + + if (service.controller[controllerName].instance === null || service.controller[controllerName].instance === undefined) { + if (_.isFunction(service.controller[controllerName].module)) { + var module = { + '$service': ['value', service.instance], + '$options': ['value', service.options[controllerName]], + '$logger': ['value', util.logger(service.name + ' - ' + controllerName)] // TODO: add logger to controller object + }; + + var InjectedModule = this.injectionDependency(module, service, service.controller[controllerName]); + + service.controller[controllerName].instance = new InjectedModule(); + // service.controller[controllerName].instance = new controller(); + } else { + service.controller[controllerName].instance = controller; } + } - return service.controller[controllerName]; + return service.controller[controllerName]; }; /** @@ -697,198 +548,203 @@ ServiceManager.prototype._setupController = function (service, route) { * @returns {*} * @private */ -ServiceManager.prototype._injectionDependency = function (module, service, parent, func) { - // --------------------------------------- - // injection dependency to Controller function - // NOTE: di does not work when you use cFunc.bind(...) as it hides the function arguments - module = _.merge({ - '$logger': ['value', logger], - '$q': ['value', when], - '_': ['value', _], - '$hyper': ['value', this._hyperCore], - '$services': ['value', this._serviceRouter], - '$http': ['value', this._httpFramework], - '$sharedConfig': ['value', this._servicesManifest.shared] - }, module); - - if (parent && parent.hasOwnProperty('config')) { - module.$config = ['value', parent.config]; - } else if (service && service.hasOwnProperty('config')) { - module.$config = ['value', service.config]; +ServiceManager.prototype.injectionDependency = function (module, service, parent, func) { + var rKey = null; + var resources = null; + + // --------------------------------------- + // injection dependency to Controller function + // NOTE: di does not work when you use cFunc.bind(...) as it hides the function arguments + module = _.merge({ + '$logger': ['value', logger], + '$q': ['value', when], + '_': ['value', _], + '$hyper': ['value', this._hyperCore], + '$services': ['value', this._serviceRouter], + '$http': ['value', this._httpFramework], + '$sharedConfig': ['value', this._servicesManifest.shared] + }, module); + + if (parent && parent.hasOwnProperty('config')) { + module.$config = ['value', parent.config]; + } else if (service && service.hasOwnProperty('config')) { + module.$config = ['value', service.config]; + } + + // TODO: do we need this??? + // add all _resources to list for DI + resources = this._resources.getAllInstances(); + for (rKey in resources) { + module[rKey] = ['value', resources[rKey]]; + } + + // add all service.resources to list for DI + if (service) { + resources = service.resources.getAllInstances(); + for (rKey in resources) { + module[rKey] = ['value', resources[rKey]]; } + } - // add all _resources to list for DI - var rKey = null; - for (rKey in this._resources) { - module[rKey] = ['value', this._resources[rKey].instance]; - } + // creates injector + var injector = new di.Injector([module]); - // add all service.resources to list for DI - if (service) { - for (rKey in service.resources) { - module[rKey] = ['value', service.resources[rKey].instance]; - } + // run function + if (func) { + if (parent) { + return injector.invoke(func, parent); + } else { + return injector.invoke(func); } + } else { + if (parent) { + if (parent.module.toString().indexOf('function') === 0) { + var InjectedWrapper = function InjectedWrapper() { + return injector.invoke(parent.module, this); + }; + // InjectedWrapper.prototype = _.merge(InjectedWrapper.prototype, parent.module.prototype); + InjectedWrapper.prototype = (0, _create2.default)(parent.module.prototype); - // creates injector - var injector = new di.Injector([module]); - - // run function - if (func) { - if (parent) { - return injector.invoke(func, parent); - } else { - return injector.invoke(func); - } - } else { - if (parent) { - if (parent.module.toString().indexOf('function') === 0) { - var InjectedWrapper = function InjectedWrapper() { - return injector.invoke(parent.module, this); - }; - //InjectedWrapper.prototype = _.merge(InjectedWrapper.prototype, parent.module.prototype); - InjectedWrapper.prototype = (0, _create2.default)(parent.module.prototype); - - return InjectedWrapper; - } else { - return injector.invoke(parent.module, this); - } - } + return InjectedWrapper; + } else { + return injector.invoke(parent.module, this); + } } - // --------------------------------------- + } + // --------------------------------------- }; +// TODO: remove this in next major version ServiceManager.prototype._setupResolver = function (service, route) { - var resolver; - var resolve = {}; - - if (!route.resolve) { - // no resolver, this is ok - return; - } else if (!_.isObject(route.resolve)) { - logger.warn("Service \"" + service.name + "\" resolver (" + route.resolve + ") invalid"); - return; + var resolve = {}; + + if (!route.resolve) { + // no resolver, this is ok + return; + } else if (!_.isObject(route.resolve)) { + logger.warn('Service "' + service.name + '" resolver (' + route.resolve + ') invalid'); + return; + } + + _.forEach(route.resolve, function (resolver, resolverBindName) { + var resolverName = 'defaultResolver'; + var resolverFile = null; + var ResolverClass = null; + + if (_.isString(resolver)) { + resolverName = resolver; + resolverFile = resolverName + '.js'; + } else if (_.isObject(resolver) && resolver.name) { + resolverName = resolver.name; + resolverFile = resolver.file; + } else { + // error + logger.warn('Service "' + service.name + '" resolver (' + resolver + ') invalid'); + return; } - _.forEach(route.resolve, function (resolver, resolverBindName) { - var resolverName = 'defaultResolver'; - var resolverFile = null; - var ResolverClass = null; - - if (_.isString(resolver)) { - resolverName = resolver; - resolverFile = resolverName + ".js"; - } else if (_.isObject(resolver) && resolver.name) { - resolverName = resolver.name; - resolverFile = resolver.file; + // resolver NOT already loaded + if (!service.resolver[resolverName]) { + if (resolverFile) { + // try to load controller as file + if (fs.existsSync(resolverFile)) { + ResolverClass = require(resolverFile); } else { + // default "/resolvers/