async-injection
Version:
A robust lightweight dependency injection library for TypeScript.
84 lines • 3.23 kB
JavaScript
import { Provider } from './provider.js';
import { isErrorObj } from './utils.js';
/**
* @inheritDoc
* This abstraction is for Providers that can be additionally configured as Singletons and/or configured with error and/or success handling callback(s).
*/
export class BindableProvider extends 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 (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));
}
}
}
//# sourceMappingURL=bindable-provider.js.map