custom.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. const is = require('is-type-of');
  3. const path = require('path');
  4. const LOAD_BOOT_HOOK = Symbol('Loader#loadBootHook');
  5. module.exports = {
  6. /**
  7. * load app.js
  8. *
  9. * @example
  10. * - old:
  11. *
  12. * ```js
  13. * module.exports = function(app) {
  14. * doSomething();
  15. * }
  16. * ```
  17. *
  18. * - new:
  19. *
  20. * ```js
  21. * module.exports = class Boot {
  22. * constructor(app) {
  23. * this.app = app;
  24. * }
  25. * configDidLoad() {
  26. * doSomething();
  27. * }
  28. * }
  29. * @since 1.0.0
  30. */
  31. loadCustomApp() {
  32. this[LOAD_BOOT_HOOK]('app');
  33. this.lifecycle.triggerConfigWillLoad();
  34. },
  35. /**
  36. * Load agent.js, same as {@link EggLoader#loadCustomApp}
  37. */
  38. loadCustomAgent() {
  39. this[LOAD_BOOT_HOOK]('agent');
  40. this.lifecycle.triggerConfigWillLoad();
  41. },
  42. // FIXME: no logger used after egg removed
  43. loadBootHook() {
  44. // do nothing
  45. },
  46. [LOAD_BOOT_HOOK](fileName) {
  47. this.timing.start(`Load ${fileName}.js`);
  48. for (const unit of this.getLoadUnits()) {
  49. const bootFilePath = this.resolveModule(path.join(unit.path, fileName));
  50. if (!bootFilePath) {
  51. continue;
  52. }
  53. const bootHook = this.requireFile(bootFilePath);
  54. if (is.class(bootHook)) {
  55. bootHook.prototype.fullPath = bootFilePath;
  56. // if is boot class, add to lifecycle
  57. this.lifecycle.addBootHook(bootHook);
  58. } else if (is.function(bootHook)) {
  59. // if is boot function, wrap to class
  60. // for compatibility
  61. this.lifecycle.addFunctionAsBootHook(bootHook);
  62. } else {
  63. this.options.logger.warn('[egg-loader] %s must exports a boot class', bootFilePath);
  64. }
  65. }
  66. // init boots
  67. this.lifecycle.init();
  68. this.timing.end(`Load ${fileName}.js`);
  69. },
  70. };