Skip to content

Instantly share code, notes, and snippets.



Last active Aug 8, 2020
What would you like to do?
How to intercept LoopBack connector's execute method to implement retry mechanism
export class DbDataSource extends juggler.DataSource
implements LifeCycleObserver {
static dataSourceName = 'db';
static readonly defaultConfig = config;
@inject('datasources.config.db', {optional: true})
dsConfig: object = config,
) {
const connector = this.connector!;
// Save the original `execute` implementation
connector._originalExecute = connector.execute;
// Inject our custom version
connector.execute = function (...params: unknown[]) {
// IMPORTANT: connectors are still callback-based
// Unfortunately, LB4 type definitions are incorrect here.
const callback = params.pop() as Function;
console.log('executing', ...params);
// forward the arguments provided by the caller
// but use our own callback to intercept the outcome
(err: unknown, ...results: unknown[]) => {
console.log('result', err, ...results);
if (!err) {
// all is good, operation was a success
callback(err, ...results);
// modify the condition to match your retry criteria
const shouldRetry = (err as any).statusCode === 429;
if (!shouldRetry) {
// unknown error, report it back to the caller
callback(err, ...results);
// retry the request after 50ms
() => void connector.execute!(...params, callback),
} as any;
// ^^^ the cast is a hack to work around incorrect typings in LB4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.