adonis-odm
Version:
A comprehensive MongoDB ODM for AdonisJS with Lucid-style API, type-safe relationships, embedded documents, and transaction support
34 lines (33 loc) • 1.42 kB
JavaScript
import { ModelQueryBuilder } from '../query_builder/model_query_builder.js';
/**
* Execute hooks for a given hook type
* Returns false if a before hook aborted the operation
*/
export async function executeHooks(target, // Target is the specific model instance or its query builder
hookType,
// modelClass is used to access the static hook methods and metadata
modelClass, ...args) {
const metadata = modelClass.getMetadata();
const hookMethodNames = metadata.hooks?.get(hookType) || [];
for (const methodName of hookMethodNames) {
const hookFn = modelClass[methodName]; // Type assertion for static method
if (typeof hookFn === 'function') {
let result;
// The hook functions are defined by the user to accept specifically typed arguments.
// The `executeHooks` function ensures the correct instance is passed.
if (target instanceof ModelQueryBuilder) {
result = hookFn.call(modelClass, target, ...args);
}
else {
result = hookFn.call(modelClass, target, ...args);
}
if (result instanceof Promise) {
result = await result;
}
if (hookType.startsWith('before') && result === false) {
return false; // Operation aborted by hook
}
}
}
return true; // Operation can proceed
}