您如何发布和订阅非 Mongo db 的数据?

How do you publish and subscribe to data that's not Mongo db?

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

本指南应该有所帮助:Publications and Data Loading

基本上,您需要了解 Meteor 的 low-level API works so that you know how to publish any data set you want to a client-side Mongo collection. Also, to publish data from other API endpoints, this part 指南如何显示一个非常清晰的示例。

至于在客户端订阅这种自定义的发布,它就像您订阅典型的 MongoDB 类型的发布一样简单。请注意,正如我上面提到的,不同之处在于,您是从 Client-side collection.

发布 to/subscribing

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


/* 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);
  });
});