@rnaga/wp-node
Version:
👉 **[View Full Documentation at rnaga.github.io/wp-node →](https://rnaga.github.io/wp-node/)**
74 lines (73 loc) • 3.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.HooksReflect = exports.ACTION = exports.FILTER = void 0;
require("reflect-metadata");
const prefix = "__REFLECT_METADATA_KEY_HOOKS_";
exports.FILTER = Symbol.for(`${prefix}FILTER__`);
exports.ACTION = Symbol.for(`${prefix}ACTION__`);
/**
* Represents a class that provides reflection utilities for defining and registering hooks.
*/
class HooksReflect {
/**
* Defines a hook for a given event name with the specified priority.
*
* @param metakey - The metadata key used for storing hook information.
* @param eventName - The name of the event.
* @param priority - The priority of the hook.
* @param args - The arguments containing the target, propertyKey, and descriptor.
*/
static define(metakey, eventName, priority, args) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [target, propertyKey, descriptor] = args;
const hookMap = Reflect.getMetadata(metakey, target.constructor) ?? new Map();
const hooks = hookMap.get(eventName) ?? [];
if (hooks.includes([priority, propertyKey])) {
return;
}
hookMap.set(eventName, [...hooks, [priority, propertyKey]]);
Reflect.defineMetadata(metakey, hookMap, target.constructor);
}
/**
* Defines a filter hook for a given event name with the specified priority.
* @param eventName - The name of the event.
* @param priority - The priority of the hook.
* @param args - The arguments containing the target, propertyKey, and descriptor.
*/
static defineFilter(eventName, priority, args) {
HooksReflect.define(exports.FILTER, eventName, priority, args);
}
/**
* Defines an action hook for a given event name.
* @param eventName - The name of the event.
* @param args - The arguments containing the target, propertyKey, and descriptor.
*/
static defineAction(eventName, args) {
HooksReflect.define(exports.ACTION, eventName, 0, args);
}
/**
* Registers the defined hooks for the given hook types, instance, and target.
*
* @param hookTypes - The hook types to register (filter and action).
* @param instance - The instance containing the hook methods.
* @param target - The target object to register the hooks on.
*/
static register(hookTypes, instance, target) {
const [filter, action] = hookTypes;
for (const metakey of [exports.FILTER, exports.ACTION]) {
const hookMap = Reflect.getMetadata(metakey, target);
for (const [eventName, values] of hookMap ?? []) {
values.forEach(([priority, propertyKey]) => {
const listener = instance[propertyKey].bind(instance);
if (metakey === exports.FILTER) {
filter.add(eventName, listener, priority);
}
else if (metakey === exports.ACTION) {
action.add(eventName, listener);
}
});
}
}
}
}
exports.HooksReflect = HooksReflect;