DataModule.ts 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import config from "config";
  2. // import { createClient, RedisClientType } from "redis";
  3. import mongoose, {
  4. MongooseDefaultQueryMiddleware,
  5. MongooseDistinctQueryMiddleware,
  6. MongooseQueryOrDocumentMiddleware
  7. } from "mongoose";
  8. import JobContext from "../JobContext";
  9. import BaseModule, { ModuleStatus } from "../BaseModule";
  10. import { UniqueMethods } from "../types/Modules";
  11. import { Models, Schemas } from "../types/Models";
  12. export default class DataModule extends BaseModule {
  13. private models?: Models;
  14. // private redisClient?: RedisClientType;
  15. /**
  16. * Data Module
  17. */
  18. public constructor() {
  19. super("data");
  20. }
  21. /**
  22. * startup - Startup data module
  23. */
  24. public override async startup() {
  25. await super.startup();
  26. const { user, password, host, port, database } = config.get<{
  27. user: string;
  28. password: string;
  29. host: string;
  30. port: number;
  31. database: string;
  32. }>("mongo");
  33. const mongoUrl = `mongodb://${user}:${password}@${host}:${port}/${database}`;
  34. await mongoose.connect(mongoUrl);
  35. await this.loadModels();
  36. // @ts-ignore
  37. // this.redisClient = createClient({ ...config.get("redis") });
  38. //
  39. // await this.redisClient.connect();
  40. //
  41. // const redisConfigResponse = await this.redisClient.sendCommand([
  42. // "CONFIG",
  43. // "GET",
  44. // "notify-keyspace-events"
  45. // ]);
  46. //
  47. // if (
  48. // !(
  49. // Array.isArray(redisConfigResponse) &&
  50. // redisConfigResponse[1] === "xE"
  51. // )
  52. // )
  53. // throw new Error(
  54. // `notify-keyspace-events is NOT configured correctly! It is set to: ${
  55. // (Array.isArray(redisConfigResponse) &&
  56. // redisConfigResponse[1]) ||
  57. // "unknown"
  58. // }`
  59. // );
  60. await super.started();
  61. }
  62. /**
  63. * shutdown - Shutdown data module
  64. */
  65. public override async shutdown() {
  66. await super.shutdown();
  67. // if (this.redisClient) await this.redisClient.quit();
  68. await mongoose.disconnect();
  69. }
  70. /**
  71. * loadModel - Import and load model schema
  72. *
  73. * @param modelName - Name of the model
  74. * @returns Model
  75. */
  76. private async loadModel<ModelName extends keyof Models>(
  77. modelName: ModelName
  78. ) {
  79. const { schema }: { schema: Schemas[ModelName] } = await import(
  80. `../schemas/${modelName.toString()}`
  81. );
  82. const preMethods: string[] = [
  83. "aggregate",
  84. "count",
  85. "countDocuments",
  86. "deleteOne",
  87. "deleteMany",
  88. "estimatedDocumentCount",
  89. "find",
  90. "findOne",
  91. "findOneAndDelete",
  92. "findOneAndRemove",
  93. "findOneAndReplace",
  94. "findOneAndUpdate",
  95. "init",
  96. "insertMany",
  97. "remove",
  98. "replaceOne",
  99. "save",
  100. "update",
  101. "updateOne",
  102. "updateMany",
  103. "validate"
  104. ];
  105. preMethods.forEach(preMethod => {
  106. // @ts-ignore
  107. schema.pre(preMethods, () => {
  108. console.log(`Pre-${preMethod}!`);
  109. });
  110. });
  111. return mongoose.model(modelName.toString(), schema);
  112. }
  113. /**
  114. * loadModels - Load and initialize all models
  115. *
  116. * @returns Promise
  117. */
  118. private async loadModels() {
  119. this.models = {
  120. abc: await this.loadModel("abc"),
  121. news: await this.loadModel("news"),
  122. station: await this.loadModel("station")
  123. };
  124. }
  125. /**
  126. * getModel - Get model
  127. *
  128. * @returns Model
  129. */
  130. public async getModel<ModelName extends keyof Models>(
  131. jobContext: JobContext,
  132. payload: ModelName | { name: ModelName }
  133. ) {
  134. if (!this.models) throw new Error("Models not loaded");
  135. if (this.getStatus() !== ModuleStatus.STARTED)
  136. throw new Error("Module not started");
  137. const name = typeof payload === "object" ? payload.name : payload;
  138. return this.models[name];
  139. }
  140. }
  141. export type DataModuleJobs = {
  142. [Property in keyof UniqueMethods<DataModule>]: {
  143. payload: Parameters<UniqueMethods<DataModule>[Property]>[1];
  144. returns: Awaited<ReturnType<UniqueMethods<DataModule>[Property]>>;
  145. };
  146. };