Using later.js to run server side API calls


#1

I’m trying to use a server side API call to update some values in a Mongo collection.

I don’t want this to be triggered by anything on the client side, but instead to run at intervals (I’m using later.js to do this).

I’m not sure where to even start, but this is what I have so far:

/server/main.js:

import * as jobs from './API_requests/github.js';
Meteor.startup(() => {
jobs.initiate_later();
});

/server/API_requests/github.js

var later = require('later');
import { HTTP } from 'meteor/http';

function tellme () {
  HTTP.call( 'GET', 'http://jsonplaceholder.typicode.com/posts', {}, function( error, response ) {
  if ( error ) {
    console.log( error );
  } else {
    console.log( response );
  }});
}

function initiate_later () {

  var git = later.parse.cron('* * * * *'); // every minute for testing
  occur = later.schedule(git).next(10);
  var execute = later.setInterval(tellme, git);
}

This just give me an error: Meteor code must always run within a Fiber.

I have a pretty strong feeling that someone is going to tell me I’m going about this in the completely wrong way. What should I be doing here instead?


#2

You’ll typically get that error if you attempt to use any Meteor code which requires a fiber. Any MongoDB methods used inside a callback would be a case in point. There’s a couple of ways to address this:

  1. Instead of the callback form of HTTP.call, use the non-callback form. That ensures the fiber is avaliable in the code that follows.
  2. Make use of Meteor.bindEnvironment or Meteor.wrapAsync to ensure the callback executes within the fiber.
  3. Use percolate:synced-cron, which provides a nice wrapper around later.js and handles all that stuff for you.

#3

Thanks! This saved me. Provides everything I need and was ridiculously easy to use.