Skip to content

Instantly share code, notes, and snippets.

@guzmonne
Created December 7, 2016 00:24
Show Gist options
  • Save guzmonne/36bb7bc2a792d2c112a1ca9588c7f23f to your computer and use it in GitHub Desktop.
Save guzmonne/36bb7bc2a792d2c112a1ca9588c7f23f to your computer and use it in GitHub Desktop.
Facebook SDK wrapper
import {facebookAppId} from '../../credentials.json'
/////////////////////////////////////////////////
function wrapFB(fb) {
// PRIVATE
/**
* Promise around FB.getLoginStatus method
*/
const _getLoginStatus = () => new Promise((resolve) => {
fb.getLoginStatus(response => resolve(response))
})
/**
* Promise around FB.login method
*/
const _login = () => new Promise((resolve, reject) => {
fb.login(response => resolve(response), {
scope: 'email,public_profile',
return_scopes: true,
})
})
/**
* Promise based workflow of Facebook login process.
* First we check that the user hasn't already logged in.
* If he is continue, else open the auth portal.
* If the authentication is succesfull return the response,
* else reject with the response.
*/
const login = () => _getLoginStatus()
.then(response => {
if (response.status === 'connected')
return response
return _login()
})
.then(response => {
if (response.status === 'connected')
return response
return Promise.reject(response)
})
/** Retun object */
return {
login
}
}
/////////////////////////////////////////////////
// Setup Facebook SDK asynchronously
/////////////////////////////////////////////////
// Instantiate a container for the wrapped SDK.
// This method will run after the SDK is downloaded.
let Facebook
window.fbAsyncInit = () => {
FB.init({
appId : facebookAppId,
status : true,
xfbml : false,
version : 'v2.8'
});
// Store the wrapped SDK on the prev defined var
Facebook = wrapFB(FB)
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
/////////////////////////////////////////////////
// Export the wrapped SDK as a function so we can
// access it from other modules. This is necessary
// because it is defined asynchronously.
export default () => Facebook
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment