【问题标题】:keep fetching data up to date保持获取最新数据
【发布时间】:2021-02-15 18:57:45
【问题描述】:

我只是想问一个问题,是否有人对此有所了解。

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

提前致谢!

【问题讨论】:

  • 我建议您从 HTTP 迁移到 WebSockets 并将您的更改流式传输到您的客户端
  • @A.H 您可以创建一个 cron 作业计划,可以根据需要设置为 5 秒后调用,这样您将在每个间隔后获得更新的用户记录。

标签: node.js node-fetch


【解决方案1】:

实现最简单的解决方案,并且在实际意义上很好地使您的网络应用程序实时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();

    }

})

现在这样你就拥有了实时的一切

【讨论】:

    猜你喜欢
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    相关资源
    最近更新 更多