DataModule.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import config from "config";
  2. import { readdir } from "fs/promises";
  3. import path from "path";
  4. import { forEachIn } from "@common/utils/forEachIn";
  5. import {
  6. Sequelize,
  7. Model as SequelizeModel,
  8. ModelStatic,
  9. DataTypes,
  10. Utils,
  11. ModelOptions,
  12. Options
  13. } from "sequelize";
  14. import { Dirent } from "fs";
  15. import * as inflection from "inflection";
  16. import { SequelizeStorage, Umzug } from "umzug";
  17. import BaseModule, { ModuleStatus } from "@/BaseModule";
  18. import DataModuleJob from "./DataModule/DataModuleJob";
  19. import Job from "@/Job";
  20. import EventsModule from "./EventsModule";
  21. export type ObjectIdType = string;
  22. // TODO fix TS
  23. // TODO implement actual checking of ObjectId's
  24. // TODO move to a better spot
  25. // Strange behavior would result if we extended DataTypes.ABSTRACT because
  26. // it's a class wrapped in a Proxy by Utils.classToInvokable.
  27. export class OBJECTID extends DataTypes.ABSTRACT.prototype.constructor {
  28. // Mandatory: set the type key
  29. static key = "OBJECTID";
  30. key = OBJECTID.key;
  31. // Mandatory: complete definition of the new type in the database
  32. toSql() {
  33. return "VARCHAR(24)";
  34. }
  35. // Optional: validator function
  36. // @ts-ignore
  37. validate(value, options) {
  38. return true;
  39. // return (typeof value === 'number') && (!Number.isNaN(value));
  40. }
  41. // Optional: sanitizer
  42. // @ts-ignore
  43. _sanitize(value) {
  44. return value;
  45. // Force all numbers to be positive
  46. // return value < 0 ? 0 : Math.round(value);
  47. }
  48. // Optional: value stringifier before sending to database
  49. // @ts-ignore
  50. _stringify(value) {
  51. return value;
  52. // return value.toString();
  53. }
  54. // Optional: parser for values received from the database
  55. // @ts-ignore
  56. static parse(value) {
  57. return value;
  58. // return Number.parseInt(value);
  59. }
  60. }
  61. // Optional: add the new type to DataTypes. Optionally wrap it on `Utils.classToInvokable` to
  62. // be able to use this datatype directly without having to call `new` on it.
  63. DataTypes.OBJECTID = Utils.classToInvokable(OBJECTID);
  64. export class DataModule extends BaseModule {
  65. private _sequelize?: Sequelize;
  66. declare _jobs: Record<string, typeof Job | typeof DataModuleJob>;
  67. /**
  68. * Data Module
  69. */
  70. public constructor() {
  71. super("data");
  72. this._dependentModules = ["events"];
  73. }
  74. /**
  75. * startup - Startup data module
  76. */
  77. public override async startup() {
  78. await super.startup();
  79. await this._setupSequelize();
  80. // await this._runMigrations();
  81. await super._started();
  82. }
  83. /**
  84. * shutdown - Shutdown data module
  85. */
  86. public override async shutdown() {
  87. await super.shutdown();
  88. await this._sequelize?.close();
  89. await this._stopped();
  90. }
  91. private async _createSequelizeInstance(options: Options = {}) {
  92. const { username, password, host, port, database } =
  93. config.get<any>("postgres");
  94. const sequelize = new Sequelize(database, username, password, {
  95. host,
  96. port,
  97. dialect: "postgres",
  98. logging: message =>
  99. this.log({
  100. type: "debug",
  101. category: "sql",
  102. message
  103. }),
  104. ...options
  105. });
  106. await sequelize.authenticate();
  107. return sequelize;
  108. }
  109. /**
  110. * setupSequelize - Setup sequelize instance
  111. */
  112. private async _setupSequelize() {
  113. this._sequelize = await this._createSequelizeInstance({
  114. define: {
  115. hooks: this._getSequelizeHooks()
  116. }
  117. });
  118. await this._sequelize.authenticate();
  119. const setupFunctions: Function[] = [];
  120. await forEachIn(
  121. await readdir(
  122. path.resolve(__dirname, `./${this.constructor.name}/models`),
  123. {
  124. withFileTypes: true
  125. }
  126. ),
  127. async modelFile => {
  128. if (!modelFile.isFile() || modelFile.name.includes(".spec."))
  129. return;
  130. const {
  131. default: ModelClass,
  132. schema,
  133. options = {},
  134. setup
  135. } = await import(`${modelFile.path}/${modelFile.name}`);
  136. const tableName = inflection.camelize(
  137. inflection.pluralize(ModelClass.name),
  138. true
  139. );
  140. ModelClass.init(schema, {
  141. tableName,
  142. ...options,
  143. sequelize: this._sequelize
  144. });
  145. if (typeof setup === "function") setupFunctions.push(setup);
  146. await this._loadModelEvents(ModelClass.name);
  147. await this._loadModelJobs(ModelClass.name);
  148. }
  149. );
  150. await forEachIn(setupFunctions, setup => setup());
  151. await this._sequelize.sync();
  152. await this._runMigrations();
  153. }
  154. /**
  155. * getModel - Get model
  156. *
  157. * @returns Model
  158. */
  159. public async getModel<ModelType extends SequelizeModel<any>>(
  160. name: string
  161. ): Promise<ModelStatic<ModelType>> {
  162. if (!this._sequelize?.models) throw new Error("Models not loaded");
  163. if (this.getStatus() !== ModuleStatus.STARTED)
  164. throw new Error("Module not started");
  165. // TODO check if we want to do it via singularize&camelize, or another way
  166. const camelizedName = inflection.singularize(inflection.camelize(name));
  167. return this._sequelize.model(camelizedName) as ModelStatic<ModelType>; // This fails - news has not been defined
  168. }
  169. private _getSequelizeHooks(): ModelOptions<SequelizeModel>["hooks"] {
  170. return {
  171. afterSave: console.log,
  172. afterCreate: async model => {
  173. const modelName = (
  174. model.constructor as ModelStatic<any>
  175. ).getTableName();
  176. let EventClass;
  177. try {
  178. EventClass = this.getEvent(`${modelName}.created`);
  179. } catch (error) {
  180. // TODO: Catch and ignore only event not found
  181. return;
  182. }
  183. EventsModule.publish(
  184. new EventClass({
  185. doc: model.get()
  186. })
  187. );
  188. },
  189. afterUpdate: async model => {
  190. const modelName = (
  191. model.constructor as ModelStatic<any>
  192. ).getTableName();
  193. let EventClass;
  194. try {
  195. EventClass = this.getEvent(`${modelName}.updated`);
  196. } catch (error) {
  197. // TODO: Catch and ignore only event not found
  198. return;
  199. }
  200. EventsModule.publish(
  201. new EventClass(
  202. {
  203. doc: model.get(),
  204. oldDoc: model.previous()
  205. },
  206. model.get("_id") ?? model.previous("_id")
  207. )
  208. );
  209. },
  210. afterDestroy: async model => {
  211. const modelName = (
  212. model.constructor as ModelStatic<any>
  213. ).getTableName();
  214. let EventClass;
  215. try {
  216. EventClass = this.getEvent(`${modelName}.deleted`);
  217. } catch (error) {
  218. // TODO: Catch and ignore only event not found
  219. return;
  220. }
  221. EventsModule.publish(
  222. new EventClass(
  223. {
  224. oldDoc: model.previous()
  225. },
  226. model.previous("_id")
  227. )
  228. );
  229. }
  230. };
  231. }
  232. private async _loadModelJobs(modelClassName: string) {
  233. let jobs: Dirent[];
  234. try {
  235. jobs = await readdir(
  236. path.resolve(
  237. __dirname,
  238. `./${this.constructor.name}/models/${modelClassName}/jobs/`
  239. ),
  240. {
  241. withFileTypes: true
  242. }
  243. );
  244. } catch (error) {
  245. if (
  246. error instanceof Error &&
  247. "code" in error &&
  248. error.code === "ENOENT"
  249. ) {
  250. this.log(
  251. `Loading ${modelClassName} jobs failed - folder doesn't exist`
  252. );
  253. return;
  254. }
  255. throw error;
  256. }
  257. await forEachIn(jobs, async jobFile => {
  258. if (!jobFile.isFile() || jobFile.name.includes(".spec.")) return;
  259. const { default: JobClass } = await import(
  260. `${jobFile.path}/${jobFile.name}`
  261. );
  262. this._jobs[JobClass.getName()] = JobClass;
  263. });
  264. }
  265. private async _loadModelEvents(modelClassName: string) {
  266. let events: Dirent[];
  267. try {
  268. events = await readdir(
  269. path.resolve(
  270. __dirname,
  271. `./${this.constructor.name}/models/${modelClassName}/events/`
  272. ),
  273. {
  274. withFileTypes: true
  275. }
  276. );
  277. } catch (error) {
  278. if (
  279. error instanceof Error &&
  280. "code" in error &&
  281. error.code === "ENOENT"
  282. )
  283. return;
  284. throw error;
  285. }
  286. await forEachIn(events, async eventFile => {
  287. if (!eventFile.isFile() || eventFile.name.includes(".spec."))
  288. return;
  289. const { default: EventClass } = await import(
  290. `${eventFile.path}/${eventFile.name}`
  291. );
  292. this._events[EventClass.getName()] = EventClass;
  293. });
  294. }
  295. private async _runMigrations() {
  296. const sequelize = await this._createSequelizeInstance({
  297. logging: message =>
  298. this.log({
  299. type: "debug",
  300. category: "migrations.sql",
  301. message
  302. })
  303. });
  304. const migrator = new Umzug({
  305. migrations: {
  306. glob: [
  307. `${this.constructor.name}/migrations/*.ts`,
  308. { cwd: __dirname }
  309. ]
  310. },
  311. context: sequelize,
  312. storage: new SequelizeStorage({
  313. sequelize: sequelize!
  314. }),
  315. logger: console
  316. });
  317. await migrator.up();
  318. await sequelize.close();
  319. }
  320. }
  321. export default new DataModule();