UNPKG

@newdash/newdash

Version:

javascript/typescript utility library

109 lines (108 loc) 3.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createFunctionWrapper = void 0; /* eslint-disable max-len */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable prefer-arrow-callback */ const isAsyncFunction_1 = require("../isAsyncFunction"); const defineFunctionName_1 = require("./defineFunctionName"); /** * @internal * @private * @ignore * @param ctx * @returns */ const defaultExecute = (ctx) => ctx.runner(...ctx.args); /** * @internal * @ignore * @private * @param ctx * @param result */ const returnSame = (ctx, result) => result; /** * @internal * @ignore * @private */ const returnUndefined = (ctx) => undefined; /** * * @internal * @ignore * @private */ const throwError = (ctx, err) => { throw err; }; /** * * create function wrapper for sync/async function * * @category Functional * @since 5.18.0 * @param runner * @param options * */ function createFunctionWrapper(runner, options) { /** * runner is async function or not */ const isAsync = (0, isAsyncFunction_1.isAsyncFunction)(runner); // return runner direct if no logic if (options.before === undefined && options.error === undefined && options.execute === undefined && options.after === undefined) { return runner; } options.after = options?.after ?? returnSame; options.before = options?.before ?? returnUndefined; options.execute = options?.execute ?? defaultExecute; // @ts-ignore options.global = options?.global ?? {}; options.error = options?.error ?? throwError; const thisContext = options.thisContext ?? this; const warpRunner = function (...args) { const ctx = { args, global: { ...(options?.global ?? {}) }, runner, state: { isAsync }, thisContext, }; try { const earlyValue = options.before.call(thisContext, ctx); if (earlyValue !== undefined) { return earlyValue; } const rt = options.execute.call(thisContext, ctx); // if return promise // @ts-ignore if (rt instanceof Promise) { ctx.state.isAsync = true; return rt .then((result) => options.after.call(thisContext, ctx, result)) // async result .catch((error) => options.error.call(thisContext, ctx, error)); // async error } // else return options.after.call(thisContext, ctx, rt); } catch (error) { // sync error return options.error.call(thisContext, ctx, error); } }; if (isAsync) { // if runner is async function, keep the warped function still an 'AsyncFunction' const asyncWarpRunner = async function (...args) { return warpRunner(...args); }; Object.assign(asyncWarpRunner, { __wrap_global__: options.global }); return (0, defineFunctionName_1.defineFunctionName)(asyncWarpRunner, runner?.name); } Object.assign(warpRunner, { __wrap_global__: options.global }); return (0, defineFunctionName_1.defineFunctionName)(warpRunner, runner?.name); } exports.createFunctionWrapper = createFunctionWrapper;