Class Hooks<TParameters, TReturn, TContext>

The Hooks class provides a convenient way to change and inspect arguments and return value of both only sync functions. For example Hooks class can be used to log function arguments and return values. Note this class will always return sync value and is immutable.

IMPORT_PATH: "@daiso-tech/core/utilities"

Type Parameters

  • TParameters extends unknown[] = unknown[]
  • TReturn = unknown
  • TContext extends Partial<Record<string, unknown>> = Partial<Record<string, unknown>>

Implements

Constructors

Methods

Constructors

  • Type Parameters

    • TParameters extends unknown[] = unknown[]
    • TReturn = unknown
    • TContext extends Partial<Record<string, unknown>> = Partial<Record<string, unknown>>

    Parameters

    Returns Hooks<TParameters, TReturn, TContext>

    import { Hooks, type MiddlewareFn } from "@daiso-tech/core/utilities";

    function log<TParameters extends unknown[], TReturn>(): MiddlewareFn<TParameters, TReturn, { funcName: string; }> {
    return (args, next, { 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 additional information to `Middleware` invokables.
    {
    funcName: add.name
    });

    // 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);

Methods