BaseModule.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import LogBook, { Log } from "./LogBook";
  2. import ModuleManager from "./ModuleManager";
  3. export enum ModuleStatus {
  4. LOADED = "LOADED",
  5. STARTING = "STARTING",
  6. STARTED = "STARTED",
  7. STOPPED = "STOPPED",
  8. STOPPING = "STOPPING",
  9. ERROR = "ERROR",
  10. DISABLED = "DISABLED"
  11. }
  12. export default abstract class BaseModule {
  13. protected moduleManager: ModuleManager;
  14. protected logBook: LogBook;
  15. protected name: string;
  16. protected status: ModuleStatus;
  17. /**
  18. * Base Module
  19. *
  20. * @param name - Module name
  21. */
  22. public constructor(name: string) {
  23. this.moduleManager = ModuleManager.getPrimaryInstance();
  24. this.logBook = LogBook.getPrimaryInstance();
  25. this.name = name;
  26. this.status = ModuleStatus.LOADED;
  27. this.log(`Module (${this.name}) loaded`);
  28. }
  29. /**
  30. * getName - Get module name
  31. *
  32. * @returns name
  33. */
  34. public getName() {
  35. return this.name;
  36. }
  37. /**
  38. * getStatus - Get module status
  39. *
  40. * @returns status
  41. */
  42. public getStatus() {
  43. return this.status;
  44. }
  45. /**
  46. * setStatus - Set module status
  47. *
  48. * @param status - Module status
  49. */
  50. public setStatus(status: ModuleStatus) {
  51. this.status = status;
  52. }
  53. /**
  54. * startup - Startup module
  55. */
  56. public async startup() {
  57. this.log(`Module (${this.name}) starting`);
  58. this.setStatus(ModuleStatus.STARTING);
  59. }
  60. /**
  61. * started - called with the module has started
  62. */
  63. protected async started() {
  64. this.log(`Module (${this.name}) started`);
  65. this.setStatus(ModuleStatus.STARTED);
  66. }
  67. /**
  68. * shutdown - Shutdown module
  69. */
  70. public async shutdown() {
  71. this.log(`Module (${this.name}) stopping`);
  72. this.setStatus(ModuleStatus.STOPPING);
  73. await this.stopped();
  74. }
  75. /**
  76. * stopped - called when the module has stopped
  77. */
  78. protected async stopped() {
  79. this.log(`Module (${this.name}) stopped`);
  80. this.setStatus(ModuleStatus.STOPPED);
  81. }
  82. /**
  83. * log - Add log to logbook
  84. *
  85. * @param log - Log message or object
  86. */
  87. protected log(log: string | Omit<Log, "timestamp" | "category">) {
  88. const {
  89. message,
  90. type = undefined,
  91. data = {}
  92. } = {
  93. ...(typeof log === "string" ? { message: log } : log)
  94. };
  95. this.logBook.log({
  96. message,
  97. type,
  98. category: `modules.${this.getName()}`,
  99. data: {
  100. moduleName: this.name,
  101. ...data
  102. }
  103. });
  104. }
  105. }