-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks.ts
More file actions
87 lines (77 loc) · 2.13 KB
/
Copy pathhooks.ts
File metadata and controls
87 lines (77 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* @file hooks.ts
* @description Provides lifecycle hooks for Stabilize ORM models, integrated with the programmatic API.
* @author ElectronSz
*/
import { MetadataStorage } from "./model";
export type HookType =
| "beforeCreate"
| "afterCreate"
| "beforeUpdate"
| "afterUpdate"
| "beforeSave"
| "afterSave"
| "beforeDelete"
| "afterDelete";
export type HookCallback = (entity: any) => Promise<void> | void;
export interface Hook {
type: HookType;
callback: HookCallback;
}
// Extend ModelConfig to include hooks
declare module "./model" {
interface ModelConfig {
hooks?: Partial<Record<HookType, HookCallback | HookCallback[]>>;
}
}
/**
* Registers hooks for a model in the MetadataStorage.
* @param model The model class.
* @param hooks A record of hook types to their callbacks.
*/
export function registerHooks(
model: Function,
hooks: Record<HookType, HookCallback | HookCallback[]>,
) {
const config = MetadataStorage.getModelMetadata(model) || {
tableName: "",
columns: {},
};
config.hooks = { ...config.hooks, ...hooks };
MetadataStorage.setModelMetadata(model, config);
}
/**
* Retrieves hooks for a given entity and hook type.
* Combines hooks from MetadataStorage and class methods.
* @param entity The entity instance.
* @param type The hook type (e.g., 'beforeCreate').
* @returns An array of Hook objects to execute.
*/
export function getHooks(entity: any, type: HookType): Hook[] {
const hooks: Hook[] = [];
if (!entity) return hooks;
const proto = Object.getPrototypeOf(entity);
if (!proto) return hooks;
const model = proto.constructor;
// Get hooks from MetadataStorage
const config = MetadataStorage.getModelMetadata(model);
if (config?.hooks?.[type]) {
const callbacks = Array.isArray(config.hooks[type])
? config.hooks[type]
: [config.hooks[type]];
hooks.push(
...callbacks.map((callback) => ({
type,
callback: () => callback(entity),
})),
);
}
// Get hooks from class methods
if (typeof entity[type] === "function") {
hooks.push({
type,
callback: () => entity[type](),
});
}
return hooks;
}