Skip to content

Instantly share code, notes, and snippets.

@saileshbro
Created July 10, 2023 02:45
Show Gist options
  • Save saileshbro/c881e34e06c7a9c62663acfc66b2a5ed to your computer and use it in GitHub Desktop.
Save saileshbro/c881e34e06c7a9c62663acfc66b2a5ed to your computer and use it in GitHub Desktop.
import { firestore, messaging } from 'firebase-admin';
import AppDb from '../enums/app_db.enum';
import { INotification } from '../interfaces/notification.interface';
import { Notification } from '../models/notification/notification.model';
import UserDetails from '../models/user/user_details.model';
import { pathToRef } from './path_to_id';
interface SendNotificationInterface
extends Omit<INotification, 'badge' | 'created_at' | 'notification_ref'> {
user?: UserDetails;
}
const sendNotifications = async (
data: SendNotificationInterface,
): Promise<unknown> => {
try {
let { receiver_ref, image_url, user } = data;
user =
user ||
UserDetails.fromDocumentSnapshot(await pathToRef(receiver_ref).get());
const image = encodeURI(image_url || user.profile_image);
const query = firestore()
.collection(AppDb.notificationsColxnName)
.where('receiver_ref', '==', receiver_ref);
const badgeRes = await query.count().get();
const badge = badgeRes.data().count + 1;
const notification_ref = firestore()
.collection(AppDb.notificationsColxnName)
.doc().path;
const notification: Notification = new Notification({
...data,
badge,
created_at: firestore.Timestamp.now(),
notification_ref,
});
await notification.save();
const tokens = user.notification_tokens || [];
if (tokens.length == 0) {
console.log(`NO TOKENS ${receiver_ref}`);
return Promise.resolve();
}
const payload = notification.payload;
console.log('PAYLOAD');
console.log(payload);
const message: messaging.MulticastMessage = {
data: payload,
tokens,
notification: undefined,
android: {
priority: 'high',
notification: undefined,
},
apns: {
fcmOptions: {
imageUrl: image,
},
payload: {
aps: {
mutableContent: true,
badge,
sound: {
name: 'default',
critical: true,
volume: 1,
},
contentAvailable: true,
},
},
},
};
return messaging()
.sendEachForMulticast(message)
.then((response) => {
if (response.failureCount == 0) return;
console.log(
response.responses
.filter((res) => !res.success)
.map((res) => res.error),
);
})
.catch((err) => {
console.error(err);
console.error('Notification Error');
});
} catch (error) {
console.error(error);
console.error('Notification Error');
return Promise.reject(error);
}
};
export default sendNotifications;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment