Class AsyncHooks<TParameters, TReturn, TContext>

The AsyncHooks class provides a convenient way to change and inspect arguments and return value of both async and sync functions. For example AsyncHooks class can be used to log function arguments and return values. Note this class will always return promise and 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/utilities"

Type Parameters

Implements

Constructors

Methods

Constructors

  • Type Parameters

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

    Returns AsyncHooks<TParameters, TReturn, TContext>

    import { AsyncHooks, type AsyncMiddlewareFn } from "@daiso-tech/core/utilities";

    function log<TParameters extends unknown[], TReturn>(): AsyncMiddlewareFn<TParameters, TReturn> {
    return async (args, next, { name: funcName }) => {
    console.log("FUNCTION_NAME:", funcName);
    console.log("ARGUMENTS:", args);
    const value = await next(...args);
    console.log("RETURN:", value);
    return value;
    }
    }

    function time<TParameters extends unknown[], TReturn>(): AsyncMiddlewareFn<TParameters, TReturn> {
    return async (args, next) => {
    const start = performance.now();
    const value = await 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 AsyncHooks(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 = await enhancedAdd.invoke(1, 2);

    // Will be 3.
    console.log(result);

Methods