index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2015 rain1017.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  12. // implied. See the License for the specific language governing
  13. // permissions and limitations under the License. See the AUTHORS file
  14. // for names of contributors.
  15. 'use strict';
  16. var path = require('path');
  17. var requireChildren = require('../../utils/require-children');
  18. var DEFAULT_BASE_PATH = 'app/controllers';
  19. var Controllers = function(app, opts){
  20. opts = opts || {};
  21. this._app = app;
  22. this._config = app.get('controllersConfig') || opts || {};
  23. this._config.basePath = this._config.basePath || DEFAULT_BASE_PATH;
  24. };
  25. var proto = Controllers.prototype;
  26. proto.name = 'controllers';
  27. proto.start = function(cb){
  28. var basePath = path.join(this._app.getBase(), this._config.basePath);
  29. this.loadControllers(basePath);
  30. cb();
  31. };
  32. proto.stop = function(force, cb){
  33. cb();
  34. };
  35. proto.loadControllers = function(basePath){
  36. var modules = requireChildren(module, basePath);
  37. var self = this;
  38. Object.keys(modules).forEach(function(name){
  39. var controller = modules[name](self._app);
  40. self[name] = controller;
  41. Object.defineProperty(self, name , {
  42. get : function(){
  43. return controller;
  44. }
  45. });
  46. });
  47. };
  48. module.exports = function(app, opts){
  49. var controllers = new Controllers(app, opts);
  50. app.set(controllers.name, controllers, true);
  51. return controllers;
  52. };