BaseModule.ts 2.0 KB

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