2021-12-06 13:12:54 +00:00
|
|
|
import lodash from 'lodash';
|
2022-02-17 08:16:05 +00:00
|
|
|
import Database from './database';
|
2022-02-23 10:18:38 +00:00
|
|
|
import { Model } from './model';
|
2022-06-08 03:22:08 +00:00
|
|
|
import type { SequelizeHooks } from 'sequelize/types/lib/hooks';
|
2021-12-06 13:12:54 +00:00
|
|
|
|
|
|
|
const { hooks } = require('sequelize/lib/hooks');
|
|
|
|
|
2022-06-08 03:22:08 +00:00
|
|
|
|
|
|
|
|
2021-12-06 13:12:54 +00:00
|
|
|
export class ModelHook {
|
|
|
|
database: Database;
|
2022-06-08 03:22:08 +00:00
|
|
|
|
|
|
|
boundEvents = new Set<string>();
|
2021-12-06 13:12:54 +00:00
|
|
|
|
|
|
|
constructor(database: Database) {
|
|
|
|
this.database = database;
|
|
|
|
}
|
|
|
|
|
2022-06-08 03:22:08 +00:00
|
|
|
match(event: string | Symbol): keyof SequelizeHooks | null {
|
|
|
|
// NOTE: skip Symbol event
|
|
|
|
if (!lodash.isString(event)) {
|
|
|
|
return null;
|
2021-12-06 13:12:54 +00:00
|
|
|
}
|
|
|
|
|
2022-06-08 03:22:08 +00:00
|
|
|
const type = event.split('.').pop();
|
|
|
|
|
|
|
|
return type in hooks ? <keyof SequelizeHooks>type : null;
|
2021-12-06 13:12:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
findModelName(hookArgs) {
|
|
|
|
for (const arg of hookArgs) {
|
2022-04-29 13:42:54 +00:00
|
|
|
if (arg?._previousDataValues) {
|
2021-12-06 13:12:54 +00:00
|
|
|
return (<Model>arg).constructor.name;
|
|
|
|
}
|
2022-03-14 05:24:00 +00:00
|
|
|
if (lodash.isPlainObject(arg)) {
|
|
|
|
if (arg['model']) {
|
|
|
|
return arg['model'].name;
|
|
|
|
}
|
2022-06-01 13:37:48 +00:00
|
|
|
const plural = arg?.name?.plural;
|
|
|
|
if (this.database.sequelize.isDefined(plural)) {
|
|
|
|
return plural;
|
|
|
|
}
|
|
|
|
const singular = arg?.name?.singular;
|
|
|
|
if (this.database.sequelize.isDefined(singular)) {
|
|
|
|
return singular;
|
2022-03-14 05:24:00 +00:00
|
|
|
}
|
2021-12-06 13:12:54 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2022-06-08 03:22:08 +00:00
|
|
|
bindEvent(type) {
|
|
|
|
this.boundEvents.add(type);
|
2021-12-06 13:12:54 +00:00
|
|
|
}
|
|
|
|
|
2022-06-08 03:22:08 +00:00
|
|
|
hasBoundEvent(type): boolean {
|
|
|
|
return this.boundEvents.has(type);
|
2021-12-06 13:12:54 +00:00
|
|
|
}
|
|
|
|
|
2022-06-08 03:22:08 +00:00
|
|
|
buildSequelizeHook(type) {
|
2021-12-06 13:12:54 +00:00
|
|
|
return async (...args: any[]) => {
|
|
|
|
const modelName = this.findModelName(args);
|
|
|
|
if (modelName) {
|
|
|
|
// emit model event
|
2022-06-08 03:22:08 +00:00
|
|
|
await this.database.emitAsync(`${modelName}.${type}`, ...args);
|
2021-12-06 13:12:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// emit sequelize global event
|
2022-06-08 03:22:08 +00:00
|
|
|
await this.database.emitAsync(type, ...args);
|
2021-12-06 13:12:54 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|