Created
December 13, 2018 18:27
-
-
Save asunwoo/c9519ea1707adc2f3575b46960421535 to your computer and use it in GitHub Desktop.
Reference Segment Optimizely Integration in Node JS Express
This file contains 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
const express = require('express') | |
const app = express() | |
const port = 80 | |
var request = require('request'); | |
var username = <Segment Workspace API username> | |
var password = '' | |
var url = 'https://profiles.segment.com/v1/spaces/<workspace_id>/collections/users/profiles/user_id:' | |
var traits = '/traits' | |
//Function that will call the personas rest api | |
function callPersonas(completeURL) { | |
return new Promise(function(resolve, reject) { | |
var options = { | |
url: completeURL, | |
auth: { | |
user: username, | |
password: password | |
} | |
} | |
request.get(options, function(err, resp, body) { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(JSON.parse(body)); | |
} | |
}) | |
}) | |
} | |
function main() { | |
app.get('/', (req, res) => { | |
//For demo purposes allowing for a query string provided user_id | |
var personaId = req.query['personaId']; | |
console.log(req.query); | |
if(personaId != null) { | |
var completeURL = url + personaId + traits; | |
var personasPromise = callPersonas(completeURL); | |
var cookieString = ''; | |
//extract industry trait from the completed rest api call. | |
personasPromise.then(function (result) { | |
userDetails = result; | |
cookieString = result['traits']['industry']; | |
}) | |
//set the retrieved industry trait as a cookie. | |
personasPromise.then(function () { | |
res.cookie('industry', cookieString); | |
//For demo purposes we're just using a screen | |
//scraped copy of the Segment home page | |
res.sendfile('index.html'); | |
}) | |
} else{ | |
//For demo purposes we're just using a screen scraped copy of the Segment home page | |
res.sendfile('index.html'); | |
} | |
}, function (err) { | |
console.log(err); | |
}) | |
} | |
app.listen(port, () => console.log(`Personas Personalized Segment app listening on port ${port}!`)) | |
app.use(express.static('public')) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment