webpush notifications from the backend side

0

I have a question about how to push the notifications from the server side, I have seen on the Internet and especially the documentation provided by Google. But I can not make the backend finish sending the notification (using nodejs) to the user who is enrolled. Someone can help. Thank you very much

On my server side I have this:

    const express = require('express');                                     // 
    incluimos librerias 
    const webpush = require('web-push');
    const bodyParser = require('body-parser');
    const path = require('path' );
    const mysql= require('mysql');

    const app= express();                                                   // creamos una variable express para la comunicacion

    app.use(bodyParser.json());

    ////////////////////////////////////////////////////////////////////////////////////////////////////




    function get_subsc_from_db(){
        conn=get_dataDB();
        var subscriptions=get_subs(conn);
        console.log("el codigo llega hasta aqui");
        return subscriptions;

    }



    function get_dataDB(){
    var connection=mysql.createConnection({
            host:'localhost',
            user:'usuario',
            password:'password',
            database:'nombre_de_basededatos',
            port:puerto

        })

        connection.connect(function(error){

            if(error){
                throw error;
            }else{
                console.log('Conexion Correcta');
            }
        });
        return connection;
    }
    function get_subs(conn){

        var subs=[];
        var aux=[];

        conn.query("select Endpoint,Key_u,Auth from usuarios where IP = '::1';",function(error,resultado){
            if(error){throw error;}

            else{
                for(i=0;i<resultado.length;i++){
                    aux[i]={"endpoint" : resultado[i].Endpoint,
                    "keys" :{
                        "auth":resultado[i].Auth,
                        "p256dh":resultado[i].Key_u
                            }   
                    }

                    subs[i]=JSON.stringify(aux[i]); console.log(subs[i]);

                }



            }
        });
        conn.close();
        return subs;
    }


    ////////////////////////////////////////////////////////////////////////////





    const publicVapidKey ='<llave publica>';            // tenemos las keys del servidor(privada y publica)
    const privateVapidKey ='<llave privada>';

    webpush.setVapidDetails('mailto:[email protected]',publicVapidKey,privateVapidKey);




    app.post('/api/trigger-push-msg/',function(req,res){

        return get_subsc_from_db().then(function(subscriptions){
            let promiseChain = Promise.resolve();
            for(i=0;i<subscriptions.length;i++){
                const subscription = subscriptions[i];
                promiseChain = promiseChain.then(()=>{
                    return triggerPushMsg(subscription,data);
                });
            }
            return promiseChain;
        })

    });

    const triggerPushMsg = function(subscription,dataToSend){
    return webpush.sendNotification(subscription,dataToSend)
        .catch((err) => {
            console.log('subscription is no longer valid:',err);
        });

    };

I'm sure I'm doing something wrong, but I do not know what. Regarding the subscriptions of users are stored in a database and from there I get them. Again, thank you very much for the help

PS: If someone can explain to me how the post () express method works I would be very grateful, in particular what I do not understand is if the directory that is specified as the first parameter is a directory that I have to create or the API of nodejs is responsible for managing everything .. ...

    
asked by k1k4ss0 21.09.2018 в 14:18
source

0 answers