Search code examples
loopbackjsloopback4

Pass custom parameters in interceptor with provider


I created an interceptor with provider and bound it to "rpc"

export class RPCProvider implements Provider<Interceptor> {

    constructor(
        @inject(CertifierBindings.CERTIFIER)
        public certifierModule: CertifierModule
    ) { }

    value() {
        return this.intercept.bind(this);
    }

    async intercept<T>(
        invocationCtx: InvocationContext,
        next: () => ValueOrPromise<T>,
    ) {

        // i want to pass some parameters in here
        // ...

        return await next();
    }
}

application.ts

this.bind('rpc').toProvider(RPCProvider);

I can use it like this:

    @intercept('rpc')
    @authenticate('basic', {
        scope: []
    })
    @post('/test/v1/anything')
    async test(): Promise<any> {
        return await this.dbMain.col("Maintainer").aggregateAndToArray([]);
    }

But how can i pass parameters every time I use it? Something like this:

    @intercept(rpc({
        a:1, // <= 
        b:2
    }))
    @authenticate('basic', {
        scope: []
    })
    @post('/test/v1/anything')
    async test(): Promise<any> {
        return await this.dbMain.col("Maintainer").aggregateAndToArray([]);
    }


Solution

  • export const MyInterceptor = function (
        ...args: any[] // <= pass custom parameters
    ): Interceptor {
        return async function (invocationCtx, next) {
             // get binding with `invocationCtx`
             const bindingObject = await invocationCtx.get<any>('binding-key');
        }
    }