function createAutoSubscribeWrapper()

in src/AutoSubscriptions.ts [117:142]


function createAutoSubscribeWrapper<T extends Function>(handler: AutoSubscribeHandler | undefined, useAutoSubscriptions: AutoOptions,
        existingMethod: T, thisArg: any): T {
    // Note: we need to be given 'this', so cannot use '=>' syntax.
    // Note: T might have other properties (e.g. T = { (): void; bar: number; }). We don't support that and need a cast.
    return function AutoSubscribeWrapper(this: any, ...args: any[]) {
        // Decorators are given 'this', but normal callers can supply it as a parameter.
        const instance = thisArg || this;

        // The handler will now be given all auto-subscribe callbacks.
        const previousHandlerWrapper = handlerWrapper;
        handlerWrapper = {
            handler: handler,
            instance: instance,
            useAutoSubscriptions: useAutoSubscriptions,
            inAutoSubscribe: false,
        };

        const result = _tryFinally(() => existingMethod.apply(instance, args),
            () => {
                // Restore the previous handler.
                handlerWrapper = previousHandlerWrapper;
            });

        return result;
    } as any as T;
}