Cloud-code that adds Facebook posts?

#1

did anyone make cloud code that adds a post to a facebook page ?

I need to do this, but wanted to see if anyone already did it ?

Thx

#2

I would probably approach it from a NodeJS perspective rather than Cloud Code. So something like this looks like it gives a decent starter for 10.

I’m using my Cloud Code more and more like a traditional NodeJS Server to interact with a number of services.

#3

i need to use cloud code because im creating a facebook post each time a new “product” is added (i’m using afterSave event)

#4

You can do something like this:

  1. Use the FB NPM package
  2. Then just us this as you would in any other function, ensuring that you do things in a sync/async way.

So, it might look something like this:

const FB = require('fb'),
const fb = new FB.Facebook(options);

//after saving a record to the FacebookPosts class perform the following
FacebookPosts.afterSave = function (req, res) {
    const fbPost = req.object;
    try {
        const fbPostResult = await performFacebookPost(fbPost);
        res.success(fbPostResult);
    } catch (e) {
        res.error(e)
    }
}

async function performFacebookPost(fbpost) {
    FB.setAccessToken('access_token');
     
    var body = fbpost.postContent;
    FB.api('me/feed', 'post', { message: body }, function (res) {
      if(!res || res.error) {
        console.log(!res ? 'error occurred' : res.error);
        return;
      }
      console.log('Post Id: ' + res.id);
    });
}

This is really rough code, but you can add in npm modules straight into the cloud code and use it as you would in any other Node app.