zync-nest-library
Version:
NestJS library with database backup and file upload utilities
93 lines (82 loc) • 2.54 kB
text/typescript
import { Injectable } from "@nestjs/common";
import * as admin from "firebase-admin";
import { Message } from "firebase-admin/lib/messaging/messaging-api";
import { INotification } from "./firebase.interface";
const rootFolder = process.cwd();
()
export class FirebaseService {
constructor() {
admin.initializeApp({
credential: admin.credential.cert(
require(`${rootFolder}/serviceAccount.json`)
),
});
}
public async sendPushNotification(
tokens: string[],
notification: INotification
) {
console.log("LOGS 1: sendPushNotification-TOKENS", tokens, notification);
if (!tokens.length) {
return;
}
try {
const response = await admin
.messaging()
.sendEachForMulticast({ tokens, ...this.buildMessage(notification) });
if (response.failureCount > 0) {
this.handleError(response.responses, tokens);
} else {
console.log(
"Push notification sent successfully:",
JSON.stringify(response)
);
}
} catch (error) {
console.error("Error sending push notification:", error);
}
}
public async sendPushNotificationToTopic(
topic: string,
notification: INotification
) {
try {
const response = await admin
.messaging()
.send({ topic, ...this.buildMessage(notification) });
console.log("Push notification sent successfully:", response);
} catch (error) {
console.error("Error sending push notification:", error);
}
}
public async subscribeToTopic(topic: string, tokens: string[]) {
await admin.messaging().subscribeToTopic(tokens, topic);
console.log("Subscribed to topic:", topic);
}
private buildMessage(notification: INotification): Message {
const message: any = {
notification: {
title: notification.title,
body: notification.body,
imageUrl: notification.image,
},
data: notification.data,
android: {
notification: {
imageUrl: notification.image, // Add image for Android
},
},
};
return message;
}
private async handleError(errors: any, tokens: string[]) {
console.error("Firebase push error", JSON.stringify(errors));
// let index = 0;
// for await (const error of errors) {
// if (error?.error.code === "messaging/registration-token-not-registered") {
// this.eventEmitter.emit("push_token.invalid", tokens[index]);
// }
// index += 1;
// }
}
}