Created
December 8, 2020 18:22
-
-
Save gurdasnijor/75ab50c98831129087739e91109aaa34 to your computer and use it in GitHub Desktop.
onbatch handler
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
// 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