push-notification.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { VercelRequest, VercelResponse } from '@vercel/node';
  2. import { initializeApp, cert } from 'firebase-admin/app';
  3. import { getFirestore } from 'firebase-admin/firestore';
  4. import { getMessaging } from 'firebase-admin/messaging';
  5. import { Message } from 'firebase-admin/lib/messaging/messaging-api';
  6. const serviceAccountStringified = Buffer.from(process.env.FIREBASE_SERVICE_ACCOUNT!, 'base64').toString('ascii');
  7. const serviceAccount = JSON.parse(serviceAccountStringified);
  8. initializeApp({
  9. credential: cert(serviceAccount),
  10. });
  11. const firestore = getFirestore();
  12. const messaging = getMessaging();
  13. export default async function sendPushNotification(req: VercelRequest, res: VercelResponse) {
  14. const { user_id, title, body } = req.query as { user_id: string; title: string; body: string };
  15. const friend = await firestore
  16. .collection('Users')
  17. .doc(user_id)
  18. .get();
  19. if (!friend.exists) {
  20. return res.status(400).json({ error: "User doesn't exist" });
  21. }
  22. const token = friend.data()!['token'];
  23. const message: Message = {
  24. notification: {
  25. title,
  26. body,
  27. },
  28. token,
  29. };
  30. messaging
  31. .send(message)
  32. .then((response) => {
  33. console.log('Successfully sent message:', response);
  34. res.status(200);
  35. })
  36. .catch((error) => {
  37. console.log('Error sending message:', error);
  38. res.status(500).send(error);
  39. });
  40. }