React Native – How to setup push notification with Firebase (4)?

How to create DB for sending notification to a specific device?

How to create related APIs?

API of getting user id, fcmToken

const Pool = require("pg").Pool;
const pool = new Pool({
  user: "postgres",
  host: "localhost",
  database: "XXXXX",
  password: "",
  port: 5432,
});

// SELECT * FROM users
const getUsers = (request, response) => {
  pool.query(
    `SELECT usr."userId", "fullName", "fcmToken", "active"
	FROM users usr LEFT JOIN devices dvc ON usr."userId" = dvc."userId"`,
    (error, results) => {
      if (error) {
        throw error;
      }
      response.status(200).json(results.rows);
    }
  );
};

2 APIs of saving user id into “users” table and saving fcmToken into “devices” table

const createUser = (request, response) => {
  const { userId, fullName } = request.body;

  pool.query(
    `INSERT INTO users("userId", "fullName") VALUES ($1, $2)
    ON CONFLICT ("userId")
    DO
    UPDATE SET "fullName" = $2`,

    [userId, fullName],
    (error, results) => {
      if (error) {
        throw error;
      } else {
        response.status(201).send({
          success: true,
          statusCode: 201,
        });
      }
    }
  );
};

///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
const createDevice = (request, response) => {
  const { deviceId, userId, fcmToken } = request.body;

  pool.query(
    `
    with i as (
      -- UPSERT an active device for a user
      INSERT INTO devices("deviceId", "userId", "fcmToken") VALUES ($1, $2, $3)
      ON CONFLICT ("deviceId")
      DO
      UPDATE SET "userId" = $2, "fcmToken" = $3
    )
      -- UPDATE other devices for this user to inactive
      UPDATE devices
      SET active = false WHERE "userId" = $2 AND "deviceId" != $1
    `,

    [deviceId, userId, fcmToken],
    (error, results) => {
      if (error) {
        throw error;
      } else {
        response.status(201).send({
          success: true,
          statusCode: 201,
        });
      }
    }
  );
};

module.exports = {
  getUsers,
  createUser,
  createDevice,
};

API of sending push notification and saving data to “notifications” table

const admin = require("firebase-admin");

const serviceAccount = require(`${firebase_private_key.json}`);

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: `${firebase_db_url}`
});

const sendFcm = (request, response) => {
  const { message, deviceToken } = request.body;

  const options = {
    priority: "high",
    timeToLive: 60 * 60 * 24,
  };

  const payload = {
    notification: {
      title: "Testing Notification",
      body: message,
    },
    data: {
      // account: "Savings",
      // balance: "$3020.25",
    },
  };

  admin
    .messaging()
    .sendToDevice(deviceToken, payload, options)
    .then(function (response) {
      console.log("Successfully sent message:", response);
    })
    .catch(function (error) {
      console.log("Error sending message:", error);
    });
};

module.exports = {
  sendFcm,
};

Be the first to comment

Leave a Reply

Your email address will not be published.


*