controller.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. 'use strict';
  2. const path = require('path');
  3. const is = require('is-type-of');
  4. const utility = require('utility');
  5. const utils = require('../../utils');
  6. const FULLPATH = require('../file_loader').FULLPATH;
  7. module.exports = {
  8. /**
  9. * Load app/controller
  10. * @param {Object} opt - LoaderOptions
  11. * @since 1.0.0
  12. */
  13. loadController(opt) {
  14. this.timing.start('Load Controller');
  15. opt = Object.assign({
  16. caseStyle: 'lower',
  17. directory: path.join(this.options.baseDir, 'app/controller'),
  18. initializer: (obj, opt) => {
  19. // return class if it exports a function
  20. // ```js
  21. // module.exports = app => {
  22. // return class HomeController extends app.Controller {};
  23. // }
  24. // ```
  25. if (is.function(obj) && !is.generatorFunction(obj) && !is.class(obj) && !is.asyncFunction(obj)) {
  26. obj = obj(this.app);
  27. }
  28. if (is.class(obj)) {
  29. obj.prototype.pathName = opt.pathName;
  30. obj.prototype.fullPath = opt.path;
  31. return wrapClass(obj);
  32. }
  33. if (is.object(obj)) {
  34. return wrapObject(obj, opt.path);
  35. }
  36. // support generatorFunction for forward compatbility
  37. if (is.generatorFunction(obj) || is.asyncFunction(obj)) {
  38. return wrapObject({ 'module.exports': obj }, opt.path)['module.exports'];
  39. }
  40. return obj;
  41. },
  42. }, opt);
  43. const controllerBase = opt.directory;
  44. this.loadToApp(controllerBase, 'controller', opt);
  45. this.options.logger.info('[egg:loader] Controller loaded: %s', controllerBase);
  46. this.timing.end('Load Controller');
  47. },
  48. };
  49. // wrap the class, yield a object with middlewares
  50. function wrapClass(Controller) {
  51. let proto = Controller.prototype;
  52. const ret = {};
  53. // tracing the prototype chain
  54. while (proto !== Object.prototype) {
  55. const keys = Object.getOwnPropertyNames(proto);
  56. for (const key of keys) {
  57. // getOwnPropertyNames will return constructor
  58. // that should be ignored
  59. if (key === 'constructor') {
  60. continue;
  61. }
  62. // skip getter, setter & non-function properties
  63. const d = Object.getOwnPropertyDescriptor(proto, key);
  64. // prevent to override sub method
  65. if (is.function(d.value) && !ret.hasOwnProperty(key)) {
  66. ret[key] = methodToMiddleware(Controller, key);
  67. ret[key][FULLPATH] = Controller.prototype.fullPath + '#' + Controller.name + '.' + key + '()';
  68. }
  69. }
  70. proto = Object.getPrototypeOf(proto);
  71. }
  72. return ret;
  73. function methodToMiddleware(Controller, key) {
  74. return function classControllerMiddleware(...args) {
  75. const controller = new Controller(this);
  76. if (!this.app.config.controller || !this.app.config.controller.supportParams) {
  77. args = [ this ];
  78. }
  79. return utils.callFn(controller[key], args, controller);
  80. };
  81. }
  82. }
  83. // wrap the method of the object, method can receive ctx as it's first argument
  84. function wrapObject(obj, path, prefix) {
  85. const keys = Object.keys(obj);
  86. const ret = {};
  87. for (const key of keys) {
  88. if (is.function(obj[key])) {
  89. const names = utility.getParamNames(obj[key]);
  90. if (names[0] === 'next') {
  91. throw new Error(`controller \`${prefix || ''}${key}\` should not use next as argument from file ${path}`);
  92. }
  93. ret[key] = functionToMiddleware(obj[key]);
  94. ret[key][FULLPATH] = `${path}#${prefix || ''}${key}()`;
  95. } else if (is.object(obj[key])) {
  96. ret[key] = wrapObject(obj[key], path, `${prefix || ''}${key}.`);
  97. }
  98. }
  99. return ret;
  100. function functionToMiddleware(func) {
  101. const objectControllerMiddleware = async function(...args) {
  102. if (!this.app.config.controller || !this.app.config.controller.supportParams) {
  103. args = [ this ];
  104. }
  105. return await utils.callFn(func, args, this);
  106. };
  107. for (const key in func) {
  108. objectControllerMiddleware[key] = func[key];
  109. }
  110. return objectControllerMiddleware;
  111. }
  112. }