【问题标题】:How to use Socket.io to update an API live如何使用 Socket.io 实时更新 API
【发布时间】:2021-05-15 06:21:52
【问题描述】:

是否可以根据数据库的变化从live api中适配json?

server.js

const connection = mongoose.connection;

connection.once("open", () => {
//Live Stream - Posts 
const observePosr_changes = connection.collection("posts").watch();
    //Observe change in Data Base
    observePosr_changes.on("change", (change) => {
        //console.log('changes right now ->',change);
        switch (change.operationType) {
            //create request
            case "insert":
                //Create posts ->  operationType function
            break;    
            //patch/put request
            case "update":
               //Update posts ->  operationType function 
            break;  
            //delete request
            case "delete":
               //Update posts ->  operationType function 
            break;  
        }
    }); 

});

我使用 mongodb 的文档发现了一种方法,通过该方法我可以在发布/修补/删除时实时检测 db atnci 中的更改

控制器/postController.js

//创建一个新帖子 - 将所有值添加到数据库中

exports.createPost = catchAsync(async(req,res)=>{
    const create = await Post.create(req.body);
       res.status(201).json({
            status:"success",
            data:create
            
    });
});

//从数据库中获取信息

exports.getAllPosts = catchAsync(async(req,res,next)=>{ 

const getAll = await Post.find()
                         
  res.status(200).json({
    status:"success",
    data:{
        post:getAll
      }
   });
});

在这种情况下是否有可能使用套接字来使应用程序生效。 也就是说,此刻移动应用和网站要看到新添加的内容必须刷新。

【问题讨论】:

    标签: node.js mongodb express websocket socket.io


    【解决方案1】:

    你要先配置服务器

      io = socket(server); -- server : express or any other 
             io.on("connection", function (socket) {
                //console.log("Made socket connection");
            });
    

    这样您就可以使用 unqiue 事件名称从客户端应用程序连接套接字

    this.socket = io.connect(YOUR_URL);
    this.socket.on(HERE_YOUR_EVENT_NAME, (data: any) => {
     -- your get the data here 
    });
    

    当您想将数据发送到客户端应用程序时,使用以下代码在服务器端使用事件名称发出数据

     io.emit(event_name, data);
    

    【讨论】:

    • 但在控制器目录中我必须导入套接字才能使用??我应该做一些像 const io = require(./server) 或类似的事情。
    猜你喜欢
    • 2014-09-04
    • 1970-01-01
    • 2021-04-19
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多