🚨 Announcing Vendure v2 Beta

Plugin Lifecycle

Since a VendurePlugin is built on top of the Nestjs module system, any plugin (as well as any providers it defines) can make use of any of the Nestjs lifecycle hooks:

  • onModuleInit
  • onApplicationBootstrap
  • onModuleDestroy
  • beforeApplicationShutdown
  • onApplicationShutdown

Note that lifecycle hooks are run in both the server and worker contexts.

Configure

Another hook that is not strictly a lifecycle hook, but which can be useful to know is the configure method which is used by NestJS to apply middleware. This method is called only for the server and not for the worker, since middleware relates to the network stack, and the worker has no network part.

Example

import { MiddlewareConsumer, NestModule, OnApplicationBootstrap } from '@nestjs/common';
import { EventBus, PluginCommonModule, VendurePlugin } from '@vendure/core';

@VendurePlugin({
    imports: [PluginCommonModule]
})
export class MyPlugin implements OnApplicationBootstrap, NestModule {

  constructor(private eventBus: EventBus) {}

  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(MyMiddleware)
      .forRoutes('my-custom-route');
  }

  async onApplicationBootstrap() {
    await myAsyncInitFunction();

    this.eventBus
      .ofType(OrderStateTransitionEvent)
      .subscribe((event) => {
        // do some action when this event fires
      });
  }
}