sql >> Database >  >> NoSQL >> MongoDB

Gegevens in Meteor invoegen vanuit Facebook API

Dacht gewoon dat het werkte. Veel dank aan Dave en emgee voor jullie hulp! Hieronder is de code voor degenen die hetzelfde probleem hebben. Laat het me ook weten als er een betere manier is om dit aan te pakken.

Servercode:

function Facebook(accessToken) {
    this.fb = Meteor.require('fbgraph');
    this.accessToken = accessToken;
    this.fb.setAccessToken(this.accessToken);
    this.options = {
        timeout: 3000,
        pool: {maxSockets: Infinity},
        headers: {connection: "keep-alive"}
    }
    this.fb.setOptions(this.options);
}

Facebook.prototype.query = function(query, method) {
    var self = this;
    var method = (typeof method === 'undefined') ? 'get' : method;
    var data = Meteor.sync(function(done) {
        self.fb[method](query, function(err, res) {
            done(null, res);
        });
    });
    return data.result;
}

Facebook.prototype.getUserData = function() {
    return this.query('me/photos');
}

Meteor.methods({
    getUserData: function() {
        var fb = new Facebook(Meteor.user().services.facebook.accessToken);
        var data = fb.getUserData();
        _.forEach(data.data, function(photo) {
            Photos.insert(photo, function(err) { 
                if(err) console.error(err); 
            });
        });
    }
});

Meteor.publish('picture', function() {
  return Photos.find();
});

Collecties:

Photos = new Meteor.Collection('picture');

Klant:

Meteor.subscribe('picture');

Template.facebookphoto.helpers({
        pictures: function () {
             return Photos.find();
          }     
});

Template.fbgraph.events({
    'click #btn-user-data': function(e) {
        Meteor.call('getUserData', function(err, data) {
             $('#result').text(EJSON.stringify(data, undefined, 4));
         });
    }
});

HTML-sjablonen:

<template name="fbgraph">
    <div id="main" class="row-fluid">
      {{> facebookphoto}}
    </div>

    <button class="btn" id="btn-user-data">Get User Data</button>
    <div class="well">
        <pre id="result"></pre>
    </div>
</template>


<template name="facebookphoto">
  <div class="photos">
    {{#each pictures}}
      {{> photoItem}}
    {{/each}}
  </div>
</template>

<template name="photoItem">
  <div class="photo">
    <div class="photo-content">
      <a href="{{source}}">
       <img class="img-rounded" src="{{picture}}">
      </a>
    </div>
  </div>
</template>