Search code examples
javascripttypescriptloopbackloopback4

How to inject middleware provider into loopback sequence


I'm following documentation here and I want to write a middleware in loopback to log all requests. I write this Middleware provider:

@injectable(
  asMiddleware({
    group: 'log',
    upstreamGroups: ['sendResponse'],
    chain: RestTags.REST_MIDDLEWARE_CHAIN,
  }),
)
export class LogMiddlewareProvider
  implements Provider<Middleware> {
  value(): Middleware {
    return async (ctx, next) => {
      const {request} = ctx
      try {
        console.log(request.method);
        const result = await next();
        return result;
      } catch (err) {
        console.log(err);
        throw err;
      }
    }
  }
}

But I can not find in documentation that how I can use this provider and how can I inject this into sequence or in my application


Solution

  • You can register it in the application.ts by importing and then registering it with the application in the constructor. Here is the example

    ....
    import { LogMiddlewareProvider } from './middleware/another.middleware';
    export class SampleAppApplication extends BootMixin(
    ServiceMixin(RepositoryMixin(RestApplication)),
    ) {
        constructor(options: ApplicationConfig = {}) {
          super(options);
          // the middleware is being registered here,
          this.middleware(LogMiddlewareProvider);
          // Set up the custom sequence
          this.sequence(MySequence);
    
          // Set up default home page
          this.static('/', path.join(__dirname, '../public'));
    
          // Customize @loopback/rest-explorer configuration here
          this.configure(RestExplorerBindings.COMPONENT).to({
            path: '/explorer',
          });
          this.component(RestExplorerComponent);
          this.projectRoot = __dirname;
          // Customize @loopback/boot Booter Conventions here
          this.bootOptions = {
            controllers: {
              // Customize ControllerBooter Conventions here
              dirs: ['controllers'],
              extensions: ['.controller.js'],
              nested: true,
          },
       };
       this.component(CrudRestComponent);
      }
    }