UNPKG

async-injection

Version:

A robust lightweight dependency injection library for TypeScript.

88 lines 3.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BindableProvider = void 0; const provider_1 = require("./provider"); const utils_1 = require("./utils"); /** * @inheritDoc * This abstraction is for Providers that can be additionally configured as Singletons and/or configured with error and/or success handling callback(s). */ class BindableProvider extends provider_1.Provider { constructor(injector, id, maker) { super(); this.injector = injector; this.id = id; this.maker = maker; } /** * Invoked by the Container to create chain-able configuration * * @see BindAs */ makeBindAs() { const retVal = { onError: (cb) => { this.errorHandler = cb; }, onSuccess: (cb) => { this.successHandler = cb; return retVal; }, asSingleton: () => { this.singleton = null; // Flag state as no longer undefined. return retVal; } }; return retVal; } /** * Encapsulate the logic of invoking any configured error handler, and processing it's result. * * @see OnErrorCallback * * @returns The object substituted by the callback (otherwise this method throws the appropriate error). */ queryErrorHandler(err, obj) { // There was an error during construction, see if an error handler was provided, and if so, see what it wants to do. if (this.errorHandler) { const handlerResult = this.errorHandler(this.injector, this.id, this.maker, err, obj); // Error handler wants us to propagate an error. if ((0, utils_1.isErrorObj)(handlerResult)) throw handlerResult; // Error handler has no opinion, so propagate the error we just caught. if (typeof handlerResult === 'undefined') throw err; // Error handler provided a valid (fully resolved) replacement. return handlerResult; } // No error handler, propagate the error we just caught. throw err; } /** * This is like a retry mechanism that uses the Provider's errorHandler (if any) to attempt recovery whenever the supplied Promise rejects. * This method returns a Promise that rejects if recovery was not possible. * If the supplied Promise resolves, then this method passes the result to the callback, and then resolve as whatever that callback returns. * * @param waitFor The supplied Promise. * @param cb Callback to be invoked if the supplied Promise resolves. */ async makePromiseForObj(waitFor, cb) { let result; try { result = await waitFor; } catch (err) { // waitFor rejected — ask the error handler for recovery, passing cb(undefined) as the partial object value. return this.queryErrorHandler(err, cb(undefined)); } try { return cb(result); } catch (err) { // cb threw after a successful resolution — ask the error handler for recovery. return this.queryErrorHandler(err, cb(result)); } } } exports.BindableProvider = BindableProvider; //# sourceMappingURL=bindable-provider.js.map