import { Hooks, type MiddlewareFn } from "@daiso-tech/core/hooks";
function log<TParameters extends unknown[], TReturn>(): MiddlewareFn<TParameters, TReturn, { funcName: string; }> {
return (args, next, { name: funcName }) => {
console.log("FUNCTION_NAME:", funcName);
console.log("ARGUMENTS:", args);
const value = next(...args);
console.log("RETURN:", value);
return value;
}
}
function time<TParameters extends unknown[], TReturn>(): MiddlewareFn<TParameters, TReturn> {
return (args, next) => {
const start = performance.now();
const value = next(...args);
const end = performance.now();
const time = end - start;
console.log("TIME:", `${String(time)}ms`);
return value;
}
}
function add(a: number, b: number): number {
return a + b;
}
const enhancedAdd = new Hooks(add, [
log(),
time()
], {
// You can provide addtional data to be used the middleware.
context: {},
});
// Will log the function name, arguments and return value.
// Will also log the execution time.
const result = enhancedAdd.invoke(1, 2);
// Will be 3.
console.log(result);
The invoke method executes the constructor's input function, applying all middlewares.
The pipe method returns a new Hooks instance with the additional middlewares applied.
The pipeWhen method conditionally applies additional middlewares, returning a new Hooks instance only if the specified condition is met.
The toFunc will return the function with all middlewares applied.
The
Hooksclass provides a convenient way to change and inspect arguments and return value of only sync functions. For exampleHooksclass can be used to log function arguments and return values. Note this class is immutable.Middlewares apply left to right: each wraps the next, with the leftmost being the outermost layer and the rightmost wrapping the original function.
IMPORT_PATH:
"@daiso-tech/core/hooks"