Shingai Munyuki
Shingai Munyuki

Reputation: 611

Inserting External, Reactive API Data into a Meteor Collection

I have some external data I'm calling from an API. The data is WordPress posts objects I'm fetching via the WordPress API.

I'm using the HTTP package and my code looks like this.

server.js

const articleIncoming = HTTP.call( 'GET', 'http://myUrl/wp-json/wp/v2/posts', {}, function( error, articleIncoming ) {
  if ( error ) {
    console.log( error );
  } else {
    console.log( articleIncoming );
 });

Where articleComing is the response. One WordPress post object looks like this in the console. This data updates with new posts on a regular basis and I would like the collection Posts, which I'm loading this data into, to reflect that.

enter image description here

Now that I have my data, I want to add these posts to a collection called Posts but I'm having difficulty.

server.js

const articleIncoming = HTTP.call( 'GET', 'http://myUrl/wp-json/wp/v2/posts', {}, function( error, articleIncoming ) {
  if ( error ) {
    console.log( error );
  } else {
    console.log( articleIncoming );
 });

 Meteor.methods({
  'Posts.insert'(articleIncoming) {
    return Posts.insert({
      articleIncoming,

    });
  },
});

Upvotes: 1

Views: 181

Answers (1)

Styx
Styx

Reputation: 10086

You are confusing Meteor methods definition with calling.

Article fetch&save code:

HTTP.get('http://myUrl/wp-json/wp/v2/posts', (error, articleIncoming) => {
  if ( error ) {
    console.log( error );
  } else {
    Meteor.call('Posts.insert', articleIncoming, (err, postId) => {
      if (err) {
        // handle error
      }
    });
  }
});

Somewhere else:

Meteor.methods({
  'Posts.insert'(articleIncoming) {
    // prevent duplications, based in article's `id` field
    const _id = `article_${articleIncoming.id}`;
    return Posts.upsert({ _id }, articleIncoming);
  },
});

Upvotes: 0

Related Questions