Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const admin = require("firebase-admin");
- const axios = require("axios");
- const { User, PushToken, Group } = PG.models;
- const fs = require('fs');
- const path = require('path');
- const serviceAccountFile = fs.readFileSync(path.resolve(__dirname, '../flutter-app-firebase-adminsdk.json'), { encoding: 'utf8' });
- const serviceAccount = JSON.parse(serviceAccountFile || "{}");
- const firebaseServerKey = process.env.FIREBASE_SERVER_KEY;
- admin.initializeApp({
- credential: admin.credential.cert(serviceAccount),
- databaseURL: process.env.FIREBASE_DB_URL
- // databaseURL: "https://push-notifications-test-a1443.firebaseio.com"
- });
- module.exports = {
- async checkToken(token){
- try {
- const result = await axios.get(`https://iid.googleapis.com/iid/info/${token}`, {
- headers:{
- Authorization: `key=${firebaseServerKey}`
- }
- });
- return !result.data.error;
- } catch (e) {
- return false;
- }
- },
- sendToToken(token, { title, body, action, navigate }){
- let skillary_obj = {};
- if(action)
- skillary_obj.skillary_action = action;
- if(navigate)
- skillary_obj.skillary_navigate = navigate;
- return admin.messaging().send({
- notification:{
- title,
- body
- },
- data:{
- click_action: "FLUTTER_NOTIFICATION_CLICK",
- ...skillary_obj
- },
- token
- });
- },
- async sendToUser(email, { title, body, action, navigate }) {
- const user = await User.findOne({
- where: {
- email,
- },
- include:[
- {
- model: PushToken,
- as: 'tokens',
- }
- ]
- });
- if(!user)
- throw new Error("No user found");
- let requests = [];
- // Iterate every token of the user
- user.tokens.map(_=>_.token).forEach( token => {
- // Send notification to token
- requests.push(
- this.sendToToken(token, { title, body, action, navigate})
- );
- });
- return Promise.all(requests);
- },
- async sendToGroup({ id, name }, { title, body }) {
- // send to user where id = id if id && email
- let paramName = id ? "id": name ? "name": null;
- let param = id? id: name? name: null;
- // If neither email or id are setted
- if(!paramName || !param)
- throw new Error("Invalid parameters");
- const group = await Group.findOne({
- where: {
- [paramName]: param
- },
- include: [{
- model: User,
- as: 'users',
- include: [{
- model: PushToken,
- as: 'tokens',
- }]
- }]
- });
- if(!group)
- return null;
- const { users } = group;
- let requests = [];
- //Iterate users
- users.forEach( user => {
- // Iterate tokens
- user.tokens.map(_=>_.token).forEach( token => {
- requests.push(this.sendToToken(token, { title, body }));
- })
- });
- return Promise.all(requests);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement