Execute module after POST request

2019-06-21 21:19发布

问题:

I'm trying to integrate sending real-time information via sockets (using socket.io), and sending push notifications using the OneSignal platform.

It happens that if I put everything in the same module, I do not know why the method to send the notification is not executed after the information is sent, or before sending the information.

If I run the command npm start no error appears but the notification arrives as soon as the local or remote server is running, and this way I do not want it to happen.

user.js

  var express = require('express');
var router = express.Router();
var misocket = require('../routes/misocket');
var notificacion = require('../routes/notificacion');

/*

run module when start server run, i don't want it

notificacion();

*/ 

/* GET users listing. sendnote*/
router.post('/sendasig', function(req, res, next) { 


    console.log(misocket);//registrednote
    misocket.emit("registrar",req.body);  
  //run here, after the send data across post request
  notificacion();
    console.log(req.body);

  res.status(200).json({
      message  : "send message"
  }); 

});

module.exports = router;

notificacion.js

 module.exports = function(){ 

        var OnesignalNotificationApi = require('onesignal-notification');
        var api = new OnesignalNotificationApi('N2FkY2ZkZWQtMGQ2MS00ZTUwLTlkM2QtODA2NmE0YjBiMzQ3',
                                        'c4b92cce-4d59-4550-a4be-20939370e39c');

        var message = {
                it: 'Some message',
                en: 'Some message',
                es: 'Nueva Calificacion'
        };

        api.sendToAll(message, null, function(err, res){
                console.log(err);
                console.log(res);
        }); 

}; 

index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

misocket.js

var i = 0;
var ioapp;

exports.connection= function(io){

    ioapp = io;

    io.on('connect',function(s){
        console.log("Conectado");    
    });

};

exports.io = ioapp;

回答1:

Replace Your notification.js with the below code

 module.exports = function(){ 

    var sendNotification = function (data) {
    var headers = {
        "Content-Type": "application/json; charset=utf-8",
        "Authorization": "Basic N2FkY2ZkZWQtMGQ2MS00ZTUwLTlkM2QtODA2NmE0YjBiMzQ3"
    };

    var options = {
        host: "onesignal.com",
        port: 443,
        path: "/api/v1/notifications",
        method: "POST",
        headers: headers
    };

    var https = require('https');
    var req = https.request(options, function (res) {
        res.on('data', function (data) {
            console.log("Response:");
            console.log(JSON.parse(data));
        });
    });

    req.on('error', function (e) {
        console.log("ERROR:");
        console.log(e);
    });

    req.write(JSON.stringify(data));
    req.end();
};

var message = {
    app_id: "c4b92cce-4d59-4550-a4be-20939370e39c",
    contents: {"en": "sample message"},
    included_segments: ["All"]
};

sendNotification(message);

}; 


回答2:

In your notification.js File the sendToAll function will be executed when the file is required (which is probably at run time for you.)

api.sendToAll(message, null, function(err, res){
    console.log(err);
    console.log(res);
}); 

You're going to want to wrap this in a function and call it inside of your post route.

module.exports = function(message){ 
  api.sendToAll(message, null, function(err, res){
     console.log(err);
      console.log(res);
   }); 
}

Which can then be required at the top of your server

 const sendMessageFunction = require('path/to/notification.js')
 .
 .
 .
 sendMessageFunction('helloWorld')


回答3:

Did you try editing user.js to be like this:

var express = require('express');
var router = express.Router();
var misocket = require('../routes/misocket');
var notificacion = require('../routes/notificacion');

var OnesignalNotificationApi = require('onesignal-notification');
var api = new OnesignalNotificationApi('N2FkY2ZkZWQtMGQ2MS00ZTUwLTlkM2QtODA2NmE0YjBiMzQ3',
                                    'c4b92cce-4d59-4550-a4be-20939370e39c');


/* GET users listing. sendnote*/
router.post('/sendasig', function(req, res, next) { 
    console.log(misocket);//registrednote
    misocket.emit("registrar",req.body);  
    //run here, after the send data across post request
    notificacion(api);
    console.log(req.body);

    res.status(200).json({
        message  : "send message"
    }); 
});

module.exports = router;

and notification.js to be like this:

module.exports = function(api){ 

    var message = {
            it: 'Some message',
            en: 'Some message',
            es: 'Nueva Calificacion'
    };

    api.sendToAll(message, null, function(err, res){
            console.log(err);
            console.log(res);
    }); 

};