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