首页 > 解决方案 > 保持获取最新数据

问题描述

我只是想问一个问题,是否有人对此有想法。

我正在构建一个由 nodejs 支持并使用 typescript 的全栈应用程序,在我的 nodejs 应用程序中,我正在获取一个 API,稍后我会将其提供给用户,但我有一个小问题,我暂时使用node-fetch,但获取的数据一直在变化,例如。现在我有 10 个条目,5 秒后我有 30 个条目,那么有没有一种方法或机制可以通过在后台获取它们来使我使用 nodejs 获取最新的数据?

提前致谢!

标签: node.jsnode-fetch

解决方案


实现网络应用程序实时的最简单的解决方案,并且在实际意义上是好的https://pusher.com/

这是您可以在 NodeJS 应用程序中处理推送器的方式

从“推动者”导入推动者

//以下是您在开始时从推送器获得的键//在您的仪表板中

const pusher = new Pusher({
  appId: "<Your app id provided by pusher>",
  key: "<Key id provided by pusher>",
  secret: "<Secret key given by pusher>",
  cluster: "<cluster given by pusher",
  useTLS: true
});

现在你想在 MongoDB 中为你的 Collection 设置一个 changeStream

const db = mongoose.collection;

db.once('open', ()=>{
    const postCollection = db.collection('posts')//This will be dependent on the collection you want to watch

    const changeStream = postCollection.watch()//Make sure the collection name above are acurate

    changeStream.on('change', (change)=>{
        
        const post = change.fullDocument;//Change bring back content that change in DB Collection
        
        if (change.operationType === 'insert'){

            pusher.triger('<write channel for your pusher>', '<event in this case inser>', {

            newPost:post

         })

        }

    })

})

通过该设置,您的推送器和后端现在正在工作,是时候设置前端了

如果您使用 VanillaJS,则 Pusher 入门有适合您的代码

如果你在这里使用 ReactJS 是下面的代码

import Pusher from 'pusher-js'

useEffect(()=>{

    Pusher.logToConsole = true;

    var pusher = new Pusher('<Key received from pusher>', {
      cluster: '<cluster received from pusher>'
    });

    var channel = pusher.subscribe('<channel name that you wrote in server');
    channel.bind('<event that you wrote in sever',(data)=> {
      alert(JSON.stringify(data)); // This will be the data entries coming as soon as they enter DB then you can update your state by using spread operators to maintain what you have and also add new contents
    });

    //Very important to have a clean-up function to render this once 

    return ()=>{

        pusher.unbind();
        pusher.unsubscribe_all();

    }

})

现在像这样,你的一切都是实时的


推荐阅读