0
votes

I want to insert in the Tweets collection every tweets from the stream made with Twit (npm module), inside a method.

Here is my code:

stream: function(hashtag) {
    //Création du stream
    stream = T.stream('statuses/filter', { track: hashtag });
    var currentHashtag = hashtag;

    // Lance le stream
    stream.on('tweet', function (tweet) {
         var userName = tweet.user.screen_name;
            var userTweet = tweet.text;
            var tweetDate = tweet.created_at;
            var profileImg = tweet.user.profile_image_url;

        console.log(userName+" a tweeté: "+userTweet+" le: "+tweetDate);
        console.log("=======================");

        Tweets.insert({user: userName, tweet: userTweet, picture: profileImg, date: tweetDate, hashtag: currentHashtag}, function(error) {
            if(error)
                console.log(error);
        });
    });
}

And here is my error message: [Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor Libraries with Meteor.bindEnvironment. ]

I've tried different solutions in vain, like wrap the Collection insertion in a Fiber(), and I try to use a Meteor.bindEnvironment, but never understand how to properly use it.

Can you help me ?

===================================================

Edit:

I've tried this. With this code, I don't have any errors anymore, but the tweets aren't inserted in my Collection.

    stream.on('tweet', Meteor.bindEnvironment(function(tweet) {
       var tweetToInsert = {
            user: tweet.user.screen_name, 
            tweet: tweet.text, 
            picture: tweet.user.profile_image_url, 
            date: tweet.created_at, 
            hashtag: currentHashtag
        };

        console.log(tweetToInsert.user+" a tweeté: "+tweetToInsert.tweet+" le: "+tweetToInsert.date+" \n "+tweetToInsert.picture+"\n"+tweetToInsert.hashtag);
        console.log("=======================");

        Tweets.insert(tweetToInsert, function(error, result) {
            if(error)
                console.log(error);
            else
                console.log(result);
        });
    }));
1
Yes, but the context is different, and I don't understand your solution, can you explain more ?Art2B
wrap your callbacks from stream.on into Meteor.bindEnvironmentimslavko
I made it, but the Tweets.insert don't work, any idea ?Art2B

1 Answers

5
votes

You can run a Fiber on insert:

var Fiber = Npm.require('fibers');
Fiber(function () {
   Tweets.insert({user: userName, tweet: userTweet, picture: profileImg, date: tweetDate, hashtag: currentHashtag}, function(error) {
      if(error)
         console.log(error);
    });
}).run();