Skip to content

Instantly share code, notes, and snippets.

@nhc
Created November 29, 2016 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nhc/f13c4defff4aeb975b78730aea82ebea to your computer and use it in GitHub Desktop.
Save nhc/f13c4defff4aeb975b78730aea82ebea to your computer and use it in GitHub Desktop.
$(function(){
$.ajaxSetup({ cache: true });
$.getScript('//connect.facebook.net/en_US/sdk.js', function(){
FB.init({
appId: '{APP_ID}', // CHANGE APP_ID
version: 'v2.3' // or v2.1, v2.2, v2.3, ...
});
});
});
// Load the Facebook SDK only once so that each time you
// get reactions, you doesn't have to get the script every time.
// Or you can download the Facebook Javascript SDK and store on your server then load from your server.
// Howerver it's totally up to you.
// var post_id = '40796308305_10155559964843306';
/**
* Get reactions for a public posts.
* @param {mixed} post_id Facebook post ID for which reactions will be pull down
* @param {Array} reactions Array of reactions. Example. ['like', 'love', 'wow', 'haha']
* @return {Promise} A promise will be return for. Return data will always have a 'err' property,
* if there is no error then 'err' would be null. For succcessfull operation respose will be in the 'data' property.
*/
function getReactions(post_id, reactions) {
var token = "USER_TOKEN"; // UPDATE THE TOKEN HERE
var query = '?fields=reactions.type(LIKE).limit(0).summary(1).as(like),reactions.type(LOVE).limit(0).summary(1).as(love),reactions.type(WOW).limit(0).summary(1).as(wow),reactions.type(HAHA).limit(0).summary(1).as(haha),reactions.type(SAD).limit(0).summary(1).as(sad),reactions.type(ANGRY).limit(0).summary(1).as(angry),reactions.type(THANKFUL).limit(0).summary(1).as(thankful)';
var full_query = post_id + query;
return new Promise(function(resolve, reject) {
if( Object.prototype.toString.call( reactions ) !== '[object Array]' ) {
reject({error: 'arguments reactions must be an array.'});
return;
}
FB.api(full_query, function(response) {
if(!response || response.error) {
reject({error: response.error});
}
var returnValue = {};
reactions.forEach(function(reaction) {
if(response.hasOwnProperty(reaction)) {
returnValue[reaction] = response[reaction]['summary']['total_count'];
}
})
resolve({err: null, data: returnValue});
return;
}, {access_token: token})
})
}
// this is how you would call the function.
getReactions(post_id, ['like', 'love', 'wow'])
.then((data) => {
console.log(data);
// Use the data to display on the web page.
// returned value sould be similar to this
// {
// like: 64,
// love: 33,
// wow: 12
// }
})
.catch(err => {
// handle errors
console.log(err);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment