UNPKG

notification-services

Version:

Use email, sms and custom notification services for node.js application easily

298 lines (266 loc) 7.91 kB
import { fcmConfig, fcmSendToToken, fcmSendMulticast, fcmSendToTopic, FCMv1, FCMConfig, FCMMessage, FCMServiceAccountKey } from '../lib'; /** * FCM v1 API Usage Examples * * This file demonstrates how to use the new FCM v1 API * which replaces the legacy FCM API with OAuth2 authentication. */ // Example 1: Configuration with service account key object const serviceAccountKey: FCMServiceAccountKey = { type: "service_account", project_id: "your-project-id", private_key_id: "key-id", private_key: "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n", client_email: "firebase-adminsdk-xxxxx@your-project-id.iam.gserviceaccount.com", client_id: "123456789", auth_uri: "https://accounts.google.com/o/oauth2/auth", token_uri: "https://oauth2.googleapis.com/token", auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs", client_x509_cert_url: "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-xxxxx%40your-project-id.iam.gserviceaccount.com" }; const fcmConfigObj: FCMConfig = { projectId: 'your-project-id', serviceAccountKey: serviceAccountKey // Can also be a path to JSON file: './path/to/service-account-key.json' }; // Configure FCM const fcm = fcmConfig(fcmConfigObj); // Example 2: Send push notification to a single device async function sendPushNotification(data: { [key: string]: string }, gcmToken: string) { try { const message: Omit<FCMMessage, 'token'> = { data: data, webpush: { fcm_options: { link: "/" }, notification: { title: data['title'], body: data['message'], image: data['image'] || '', icon: '/logo.png', }, } }; // Optional: Add Android configuration // message.android = { // notification: { // title: data['title'], // body: data['message'], // image: data['image'] || '', // }, // }; const result = await fcmSendToToken(gcmToken, message); if (result.error) { console.error('FCM Error:', result.error); return false; } console.log('FCM Success:', result); return result; } catch (error) { console.error('FCM Send Error:', error); return false; } } // Example 3: Advanced usage with full message customization async function sendAdvancedNotification() { const token = 'user-device-token'; const message: Omit<FCMMessage, 'token'> = { // Data payload (key-value pairs, all values must be strings) data: { userId: '123', action: 'newMessage', timestamp: Date.now().toString() }, // Cross-platform notification notification: { title: 'New Message', body: 'You have a new message', image: 'https://example.com/image.jpg' }, // Android-specific configuration android: { priority: 'high', notification: { title: 'New Message (Android)', body: 'You have a new message on Android', icon: 'stock_ticker_update', color: '#ff0000', sound: 'default', channel_id: 'messages', click_action: 'FLUTTER_NOTIFICATION_CLICK' }, fcm_options: { analytics_label: 'android_notification' } }, // Web push configuration webpush: { headers: { TTL: '300' }, notification: { title: 'New Message (Web)', body: 'You have a new message on web', icon: '/images/icon-192x192.png', badge: '/images/badge-72x72.png', actions: [ { action: 'view', title: 'View Message' }, { action: 'dismiss', title: 'Dismiss' } ], requireInteraction: true, tag: 'message-notification' }, fcm_options: { link: '/messages', analytics_label: 'web_notification' } }, // iOS (APNs) configuration apns: { headers: { 'apns-priority': '10', 'apns-expiration': String(Math.floor(Date.now() / 1000) + 3600) }, payload: { aps: { alert: { title: 'New Message (iOS)', body: 'You have a new message on iOS' }, badge: 1, sound: 'default', category: 'MESSAGE_CATEGORY', 'content-available': 1, 'mutable-content': 1 }, customData: { messageId: '123', senderId: '456' } }, fcm_options: { analytics_label: 'ios_notification', image: 'https://example.com/ios-image.jpg' } }, // Global FCM options fcm_options: { analytics_label: 'general_notification' } }; try { const result = await fcmSendToToken(token, message); console.log('Advanced notification sent:', result); return result; } catch (error) { console.error('Failed to send advanced notification:', error); throw error; } } // Example 4: Send to multiple tokens (multicast) async function sendToMultipleDevices() { const tokens = [ 'token1', 'token2', 'token3' ]; const message: Omit<FCMMessage, 'token'> = { notification: { title: 'Broadcast Message', body: 'This message is sent to multiple devices' }, data: { type: 'broadcast', timestamp: Date.now().toString() } }; try { const result = await fcmSendMulticast(tokens, message); console.log(`Sent to ${result.successCount} devices, ${result.failureCount} failed`); // Handle individual responses result.responses.forEach((response, index) => { if (response.error) { console.error(`Failed to send to token ${tokens[index]}:`, response.error); } else { console.log(`Successfully sent to token ${tokens[index]}:`, response.name); } }); return result; } catch (error) { console.error('Multicast send failed:', error); throw error; } } // Example 5: Send to topic async function sendToTopic() { const message: Omit<FCMMessage, 'topic'> = { notification: { title: 'Topic Notification', body: 'This is sent to all devices subscribed to the topic' }, data: { type: 'topic_message' } }; try { const result = await fcmSendToTopic('news', message); console.log('Topic message sent:', result); return result; } catch (error) { console.error('Topic send failed:', error); throw error; } } // Example 6: Using the FCMv1 class directly (alternative approach) async function usingFCMClassDirectly() { const fcmClient = new FCMv1({ projectId: 'your-project-id', serviceAccountKey: './path/to/service-account-key.json' }); const result = await fcmClient.sendToToken('device-token', { notification: { title: 'Direct Class Usage', body: 'This uses the FCMv1 class directly' } }); console.log('Direct class result:', result); return result; } // Example usage async function main() { try { const data = { title: 'Test Notification', message: 'This is a test message', image: 'https://example.com/image.jpg' }; const result = await sendPushNotification(data, 'user-device-token'); if (result) { console.log('FCM Response:', result); } } catch (error) { console.error('Main execution error:', error); } } export { sendPushNotification, sendAdvancedNotification, sendToMultipleDevices, sendToTopic, usingFCMClassDirectly, };