Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

node.js - How to use socket.io to reflect one api changes in another api without loading?

I've a node api(POST)in which the sensor keep on pushing the data to the MongoDB. Now I've an api(GET) which fetches the data from the database and displays on the dashboard. To get the continuous stream of data, I want to use SOCKET.IO module. But the problem is, how could I get the recently saved record from the db and show that on dashboard without reloading the page. Please have a look at my code.

SERVER.JS

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
// and manything like router, middleware, etc...    

io.on('connection', function(socket){
    console.log('a user connected');
});
http.listen(3000, function(){
    console.log('listening on port:3000');
});

ROUTES FILE

var router = require("express").Router();
router.post("/upload/device/data/:tempId", TemplateController.AddDeviceData); //To insert the data to the DB
router.get("/view/template/device/logs/:tempUniqID", TemplateController.deviceLogs);  //To get the data from DB

TEMPLATE CONTROLLER FILE

module.exports={
    AddDeviceData:async function(req, res){ //Controller to post data
       let err, deviceLog;

       [err, deviceLog]=await     
    to(TemplateService.AddDeviceLogs(req.params.tempId, req.body));
        if(err) return res.serverError(err.message);
        if(deviceLog&&deviceLog!==false){
            return res.ok(deviceLog);
        }else{
            res.badRequest("Sorry cannot add Device log data");
        }
    },

    deviceLogs: async function(req, res){ //Controller to fetch data
        let err, logs;
        let deviceId = req.query.device;
        [err, logs]=await to(TemplateService.displayLogs(req.params.tempUniqID, deviceId));
        if(err) return res.serverError(err.message);
        if(logs&&logs!==false){
            return res.ok(logs);
        }else{
            res.badRequest("Sorry cannot add Device log data");
        }
    }
}

TEMPLATE SERVICE FILE

module.exports={
    //Service to post data
    AddDeviceLogs:async function(templateId, payload){
        let err, deviceData;
        payload.template=templateId;
        const myCollection=templateId;

        [err, deviceData]=await to(mongoose.connection.db.collection(myCollection).insert(payload));
        if(err) TE(err.message, true);
        socket.emit('data', deviceData);
        return (deviceData)? deviceData.result:false;
    },

    //Service to get data
    displayLogs:async function(tempUniqID, deviceID){
        let err, respData;

        var Query = (deviceID)? {"template": tempUniqID, "deviceId": deviceID}:{template: tempUniqID};
        [err, respData]=await to(mongoose.connection.db.collection(tempUniqID).find(Query).sort({_id: -1}).limit(20).toArray())
        if(err) {TE(err, true);}
        return (respData)? respData:false;
    }
}

Now I want to get most recently stored data in GET api using socket without reloading the page or without executing the GET route-api. I'm not getting which service I should use server socket-emit event in and how.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can run node and your socket io in the same port, the following example used express and socket.io. I also created sensor code to imagine this solution:

You should use your route file like this:

ROUTES FILE

var router = require("express").Router();
router.post("/upload/device/data/:tempId", TemplateController.AddDeviceData);
router.get("/", function (req, res, next) {
    res.sendFile('C:/Users/user/Desktop/data.html');
})

In MVC you will have a root file declare all works, you should delare your socket here.

Because in your codebase, every time you call AddDeviceLogs function, it will re-declare websocket, and your socket client in html file will disconnect, that's why it only work for the first time.

Then you should declare it global, for example:

server.js

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
// and manything like router, middleware, etc...    

io.on('connection', function(socket){
    console.log('a user connected');
});
http.listen(3000, function(){
    console.log('listening on port:3000');
});

TEMPLATE SERVICE FILE

module.exports={
    AddDeviceLogs:async function(templateId, payload){
        let err, deviceData;
        payload.template=templateId;
        const myCollection=templateId;

        io.emit('data', payload)  // emit to all client

        [err, deviceData]=await to(mongoose.connection.db.collection(myCollection).insert(payload));
        if(err) TE(err.message, true);
        return (deviceData)? deviceData.result:false;
    }
}

data.html

<html>
    <head>
        <script src="/socket.io/socket.io.js"></script>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
    </head>
    <body>
        <script>
        var socket = io.connect("http://localhost:3000/",{"forceNew": true});
        socket.on('data', function(data){
            if (data) {
                $('#deviceid').text(data.deviceId);
                $('#heat').text(data.heat);
                $('#humidity').text(data.humidity);
            }
        });

        </script>
        <h4>Welcome to socket.io testing program!</h4>
        <div id="deviceid"></div>
        <div id="heat"></div>
        <div id="humidity"></div>
    </body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...