BaseModule.ts 2.0 KB

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