首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使获取的数据保持最新

使获取的数据保持最新
EN

Stack Overflow用户
提问于 2020-11-03 13:04:47
回答 1查看 188关注 0票数 0

我只想问一个问题,如果有人对此有想法的话。

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

提前感谢!

EN

回答 1

Stack Overflow用户

发布于 2020-11-03 14:58:45

使您的web应用程序实现实时https://pusher.com/的最简单且实际意义上最好的解决方案

这是您在NodeJS应用程序中处理pusher的方式

从' Pusher‘导入pusher

//下面是您在仪表板中转到入门//时将从pusher获得的密钥

代码语言:javascript
复制
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中为收藏设置changeStream

代码语言:javascript
复制
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

         })

        }

    })

})

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

If your usin VanillaJS the Pusher getting started有适合您的代码

如果您使用ReactJS,这里的代码是下面的代码

代码语言:javascript
复制
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();

    }

})

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64657070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档