简体   繁体   中英

meteor.js - temporary server-side app state

I need to use some data from a 3rd party API in my app, poll for the needed data with certain frequency from the server, and make it available to the client. The easiest way would be to create a collection and update it, and make the data available to the client via pub/sub. But, in this particular case I don't need to store that data or keep track of it, and it updates very frequently, so storing it to db would actually be just additional unneeded work. I would prefer to store it somehow in the RAM, and make it available to the client in some other way except collections (perhaps, return from a method call). But I'm not sure, how to do that. Could someone suggest some nice approach?

You could use this package meteor-publish-join to fetch data from external API and publish to client periodically (disclaimer: I am the author):

Server:

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));
    },
  });
});

Client:

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

Meteor.subscribe('test');

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM