1.0.0 • Published 2 years ago

@pavlokobyliatskyi/firebase-messaging v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

NestJs Firebase Messaging

A push-notification helper module for Nestjs to send push notifications to mobile devices

Installation

npm install @nestjs/firebase-messaging --save

How to use it?

Import FirebaseMessagingModule into your notification module, set necessary fields for module initialization, embed PushNotificationService of notifications into your module via FirebaseMessagingModule.PUSH_NOTIFICATION_SERVICE, create a message using the Builders and send it using the embedded service

@Module({
  imports: [
    FirebaseMessagingModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => {
        return {
          projectId: configService.getProjectId(),
          privateKey: configService.getPrivateKey(),
          clientEmail: configService.getClientEmail(),
        };
      },
      inject: [ConfigService],
    }),
  ],
})
export class NotificationModule implements OnModuleInit {
  constructor(
    @Inject(FirebaseMessagingModule.PUSH_NOTIFICATION_SERVICE)
    private readonly pushNotificationService: IPushNotificationService,
  ) {}

  public async onModuleInit() {
    const notification = new NotificationBuilder()
      .setTitle('title')
      .setBody('body')
      .build();

    const message = new MessageBuilder()
      .setNotification(notification)
      .setToken('fcm-token')
      .setData({ field: 'value' })
      .build();

    await this.pushNotificationService.sendToDevice(message);
  }
}