Last active
February 28, 2019 23:36
-
-
Save asaschachar/cb81e35ebccb3f1739bc611a097ab71d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Optimizely Node Datafile Manager | |
* | |
* | |
* USAGE - INSTALLATION | |
* // Pre-requisites: npm install --save request-promise request @optimizely/optimizely-sdk | |
* // Save this file in a file named optimizely-manager.js | |
* const createOptimizelyManager = require('./optimizely-manager') | |
* const optimizelyManager = createOptimizelyManager('Ly8FQj6vSaDcZUjySoWnWz') | |
* | |
* USAGE - USING A FEATURE FLAG | |
* const optimizelyClient = optimizelyManager.getClient() | |
* const enabled = optimizelyClient.isFeatureEnabled('sale_price', userId); | |
* | |
*/ | |
const request = require('request-promise'); | |
const assert = require('assert'); | |
const optimizely = require('@optimizely/optimizely-sdk'); | |
module.exports = (SDK_KEY) => { | |
let currentDatafile = {}; | |
let optimizelyClientInstance = optimizely.createInstance({ datafile: currentDatafile }); | |
function pollForDatafile() { | |
// Request the datafile every second. If the datafile has changed | |
// since the last time we've seen it, then re-instantiate the client | |
const DATAFILE_URL = `https://cdn.optimizely.com/datafiles/${SDK_KEY}.json`; | |
request(DATAFILE_URL) | |
.then(async (latestDatafile) => { | |
try { | |
assert.deepEqual(currentDatafile, latestDatafile) | |
} catch (err) { | |
console.log('Got a new datafile!') | |
// The datafile is different! Let's re-instantiate the client | |
optimizelyClientInstance = optimizely.createInstance({ latestDatafile }); | |
currentDatafile = latestDatafile; | |
} | |
}) | |
} | |
setInterval(pollForDatafile, 1000); | |
return { | |
getClient: () => { | |
return optimizelyClientInstance; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment