如何发布和订阅非 Mongodb 的数据?

2024-02-06

Meteor.publish 设置执行一些异步请求(例如 API)然后返回要在 React 组件中显示的数据的过程是什么?发布是如何工作的以及客户端代码如何访问它?如果可能的话,我想用 withTracker 函数来做到这一点。谢谢!


本指南应该有助于:出版物和数据加载 https://guide.meteor.com/data-loading.html.

基本上,你需要了解 Meteor 是如何低级API https://guide.meteor.com/data-loading.html#custom-publication使您知道如何将所需的任何数据集发布到客户端 Mongo 集合。此外,要发布来自其他 API 端点的数据,这部分 https://guide.meteor.com/data-loading.html#loading-from-rest该指南显示了一个非常清晰的示例。

至于在客户端订阅这种自定义出版物,就像订阅典型的 MongoDB 类型出版物一样简单。请注意,区别在于,正如我上面提到的,您正在发布到/订阅客户端集合 https://guide.meteor.com/collections.html#client-collections.

下面是我自己写的一个简单的例子。我不太了解React,但是客户端代码主要基于Meteor的教程:

  • 收藏 https://www.meteor.com/tutorials/react/collections
  • 发布和订阅 https://www.meteor.com/tutorials/react/publish-and-subscribe

/* client side */
import React, { Component } from 'react';
import { withTracker } from 'meteor/react-meteor-data';
import { Meteor } from 'meteor/meteor'; 
import { Mongo } from 'meteor/mongo';

const Foo = new Mongo.Collection('Foo');

class App extends Component {
  renderFoo() {
    return this.props.foos.map((foo) => (
      <Foo key={foo._id} foo={foo} />
    ));
  }
}

export default withTracker(() => {
  Meteor.subscribe('publishFromAnApi', ...args);
  return {
    foos: Foo.find().fetch(),
  };
})(App);


/* server side */
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';

Meteor.publish('publishFromAnApi', function publishFromAnApi(...args) {  // must use a function instead of an arrow function here for the sake of `this`
  const publishedKey = {};
  const collectionName = 'Foo'; // same name of the client side collection mentioned in line 6

  const poll = () => {
    const { data } = HTTP.get('/some/api/route', { ...someArgsToRequest });
    for (let i = 0; i < data.responseFromAPI; i += 1) { // just a random example here, assuming responseFromAPI is an array
      const document = data.responseFromAPI[i];
      const id = <the id of the document; normally is in Mongo.ObjectID type>;

      // some logics might be going on...

      if (!publishedKey[id]) {
        this.added(collectionName, id, document);
        publishedKey[id] = true;
      } else {
        this.changed(collectionName, id, document);
      }
    }
  };

  poll();
  this.ready();

  const interval = Meteor.setInterval(poll, <poll interval>);

  this.onStop(() => {
    Meteor.clearInterval(interval);
  });
});

meteor /questions/tagged/meteor

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何发布和订阅非 Mongodb 的数据? 的相关文章

随机推荐