meteor.js - 临时服务器端应用程序状态

时间:2017-02-20 09:54:40

标签: javascript meteor

我需要在我的应用中使用来自第三方API的一些数据,从服务器以特定频率轮询所需数据,并将其提供给客户端。最简单的方法是创建一个集合并对其进行更新,并通过pub / sub将数据提供给客户端。但是,在这种特殊情况下,我不需要存储该数据或跟踪它,并且它经常更新,因此将其存储到db实际上只是额外的不必要的工作。我更愿意将它以某种方式存储在RAM中,并以除了集合之外的其他方式将其提供给客户端(可能从方法调用返回)。但我不确定,怎么做。有人可以建议一些不错的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用此包meteor-publish-join从外部API获取数据并定期发布到客户端(免责声明:我是作者):

服务器:

import { JoinServer } from 'meteor-publish-join';

Meteor.publish('test', function() {

  // Publish a random value from an external API, plays well with promise, re-run every 10 seconds
  JoinServer.publish({
    context: this,
    name: 'withPromise',
    interval: 10000,
    doJoin() {
      const id = parseInt(Math.random() * 100, 10);

      return fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
        .then(res => res.json())
        .then(data => data.title)
        .catch(err => console.error(err));
    },
  });
});

客户端:

从'meteor-publish-join'导入{JoinClient};

Meteor.subscribe('test');

// Get the values published within `test` publication. All these values are reactive
JoinClient.get('withPromise')