Skip to content

Instantly share code, notes, and snippets.

@gurdasnijor
Created December 8, 2020 18:22
Show Gist options
  • Save gurdasnijor/75ab50c98831129087739e91109aaa34 to your computer and use it in GitHub Desktop.
Save gurdasnijor/75ab50c98831129087739e91109aaa34 to your computer and use it in GitHub Desktop.
onbatch handler
// The function runnning this code will be automatically provisioned when a user clicks the
// "create integration" button at the end of the creation flow -- it'll thread various bits
// of config down to the batch handler like profile -> destination mappings, auth tokens, and other
// context needed to interact with a partner api
async function onBatch(events, { endpoint, mappings, token }) {
//The mappings object is a dictionary of traitField->destinationField, lets retrieve all the
//traits we need from the profile api
// Map over all "Audience Entered" and "Audience Exited" events to produce
// enriched integration request payloads
const audienceEnteredRequest = events.map(user => {
const profileData = profiles.get(user.segment_id, Object.keys(mappings))
return {
...user,
...profileData
}
})
let response
try {
response = await fetch(endpoint, {
method: 'POST',
headers: {
Authorization: `Basic ${btoa(token + ':')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(audienceEnteredRequest)
});
} catch (error) {
// Retry on connection error
throw new RetryError(error.message)
}
if (response.status >= 500 || response.status === 429) {
// Retry on 5xx (server errors) and 429s (rate limits)
throw new RetryError(`Failed with ${response.status}`)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment