How to Insert json data from an api into a Collection


#1

Using this Meteor package redcap3000:wordpress-json-api for displaying wordpress posts via wordpress api in json format, I managed to successfully display them in my meteor app. However I need to save the posts in my mongo db collections AS WELL AS updating the collection automatically when a new post is available at my wordpress site, how can i do that?

here is what i have so far.

` MyCollection = new Mongo.Collection(‘Articles’);
saveArticles: function() {
Meteor.call(‘wordpress’,‘http://my-wordpress-site/?json=get_posts&count=10’, function(err, res) {
var data = res.title;
MyCollection.insert(data);
}
}

Meteor.subscribe(“wordpress”,“http://my-wordpress-site/?json=get_posts&count=10”);

Session.setDefault(“wp-json-api-url”,“http://my-wordpress-site/?json=get_posts&count=10”);`

server side code

`Meteor.startup(function(){
Meteor.setInterval(function(){Meteor.call(‘http://my-wordpress-site/?json=get_posts&count=10’);}, 1000);
});

Meteor.publish(“wpPost”,function(id){})`

error

While processing files with ecmascript (for target web.browser): lib/collections.js:6:22: Unexpected token (6:22)

which relates to the first line of this code i (the one i put above, in my client folder)

saveArticles: function() { Meteor.call('wordpress','http://my-wordpress-site/?json=get_posts&count=10', function(err, res) { var data = res.title; MyCollection.insert(data); } }

overall i’m not sure if i’m going the right direction.


#2

A fairly typical, basic pattern for a JSON endpoint is to do something like this on the server:

Meteor.startup(() => {
  function getData() {
    try {
      const result = HTTP.get(url, headers);
      result.data.forEach(doc => {
        myCollection.insert(doc);
      });
    } catch (err) {
      throw new Meteor.Error('oops', 'something bad happened');
    }
    Meteor.setTimeout(getData, 60000);
  }
  getData();
});

However, this pattern will need work to deal with lots of things, including de-duplicating data (where you get the some of the same posts back), storing the data you need (instead of everything), adding metadata, etc.

You could also look at packages like https://atmospherejs.com/okgrow/rest2ddp


Import Meetup API -Meteor
#3

yes i got it using the ddp package! thank you for your help!!