Firebase Cloud Messaging SDK Admin
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.5 KiB

  1. const express = require("express");
  2. require('dotenv').config();
  3. const path = require("path");
  4. var admin = require("firebase-admin");
  5. const port = process.env.PORT || 14003;
  6. var dirPath = path.join(__dirname, "fcm_key");
  7. var data = require("./keypath.json");
  8. const { messaging } = require("firebase-admin");
  9. //dijadiin 1 ThamrinGroup dan HRIS
  10. // for (key in keyPath) {
  11. var jsonPath = path.join(dirPath, data.PATH);
  12. var adminAuthToken = require(jsonPath);
  13. admin.initializeApp(
  14. {
  15. credential: admin.credential.cert(adminAuthToken),
  16. databaseURL: process.env.DB_URL,
  17. },
  18. // key
  19. );
  20. // }
  21. const app = express();
  22. app.use(
  23. express.json({ limit: "50mb", parameterLimit: 1000000, extended: true })
  24. );
  25. app.use(
  26. express.urlencoded({ limit: "50mb", parameterLimit: 1000000, extended: true })
  27. );
  28. app.post("/sendFcm", async function (req, res) {
  29. try {
  30. var message = req.body;
  31. console.log(message);
  32. if(message){
  33. messaging().sendMulticast(message)
  34. .then((response) => {
  35. // console.log(response.successCount + ' messages were sent successfully');
  36. if (response.failureCount > 0) {
  37. if(message.tokens){
  38. const failedTokens = [];
  39. response.responses.forEach((resp, idx) => {
  40. if (!resp.success) {
  41. failedTokens.push(message.tokens[idx]);
  42. }
  43. });
  44. console.log("Failed Fcm Notif",failedTokens);
  45. return res.status(400).json(response);
  46. }
  47. else{
  48. return res.status(400).json({error:"Error sending FCM Notification!"});
  49. }
  50. }
  51. return res.status(200).json(response);
  52. }).catch((error) => {
  53. return res.status(404).json(error);
  54. });
  55. }
  56. else{
  57. return res.status(404).json({error:"Message can't be empty!"});
  58. }
  59. // var fcm = admin.app(application.application);
  60. // fcm
  61. // .messaging()
  62. // .sendMulticast(message)
  63. // .then((response) => {
  64. // if (response.failureCount > 0) {
  65. // const failedTokens = [];
  66. // response.responses.forEach((resp, idx) => {
  67. // if (!resp.success) {
  68. // failedTokens.push(registrationTokens[idx]);
  69. // }
  70. // });
  71. // }
  72. // return res.status(200).json(response);
  73. // })
  74. // .catch((error) => {
  75. // return res.status(404).json(error);
  76. // });
  77. } catch (e) {
  78. console.log(e.message);
  79. return res.status(404).json(e.message);
  80. }
  81. });
  82. app.listen(port, () => console.log(`Listening into port ${port}`));