Untitled

 avatar
user_5257650
plain_text
7 months ago
2.0 kB
2
Indexable
Never
const { default: axios } = require('axios');

const prisma = require('../../../prisma');

const sendNotification = async data => {
    const appSettings = await prisma.AppSettings.findUnique({
        where: { name: 'app_settings' }
    });

    const imageUrl = data.image_url;
    const notificationTitle = data.title;
    const notificationMessage = data.message;
    const firebaseTopics = appSettings.firebase_topics;
    const firebaseServerKey = appSettings.firebase_key;
    const url = 'https://fcm.googleapis.com/fcm/send';

    const dataArr = {
        title: notificationTitle,
        body: notificationMessage,
        style: 'picture',
        image: imageUrl,
        notification_type: data.notification_type,
        action_url: data.action_url
    };

    const notificationData = {
        title: notificationTitle,
        body: notificationMessage,
        image: imageUrl,
        style: 'picture',
        android: {
            notification: {
                notificationCount: 1
            }
        },
        apple: {
            notification: {
                notificationCount: 1
            }
        }
    };

    const android = {
        notification: {
            image: imageUrl
        }
    };

    const arrayToSend = {
        to: `/topics/${firebaseTopics}`,
        data: dataArr,
        priority: 'high',
        notification: notificationData,
        android: android
    };

    const headers = {
        Authorization: `key=${firebaseServerKey}`,
        'Content-Type': 'application/json'
    };

    async function sendNotification() {
        try {
            const response = await axios.post(url, arrayToSend, { headers: headers });
            console.log('Notification sent successfully:', response.data);
        } catch (error) {
            console.error('Error sending notification:', error.message);
        }
    }

    sendNotification();
};

module.exports = sendNotification;
Leave a Comment