Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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:mail@test.com',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);
- });
- };
Add Comment
Please, Sign In to add comment