Created
October 18, 2019 18:48
-
-
Save tiffwu/2e3210d578f6ddbd97968eb38f0ecfc9 to your computer and use it in GitHub Desktop.
event aggregator
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 VALID_EVENTS = ["searchChanged", "jobViewed", "applicationSubmitted"]; | |
async function process(api) { | |
try { | |
const events = await api("GET", "/events"); | |
const { invalid, counts } = categorizeEvents(events); | |
await Promise.all([ | |
api("POST", "/counts", counts), | |
api("POST", "/invalid", invalid) | |
]); | |
return true; | |
} catch (_e) { | |
return false; | |
} | |
} | |
function categorizeEvents(events) { | |
const invalid = new Set(); | |
const counts = {}; | |
categorize(events); | |
function categorize(evts) { | |
evts.forEach(event => { | |
if (Array.isArray(event)) { | |
return categorize(event); | |
} | |
if (VALID_EVENTS.includes(event.name)) { | |
counts[event.name] = (counts[event.name] || 0) + 1; | |
} else { | |
invalid.add(event.name); | |
} | |
}); | |
} | |
return { invalid: Array.from(invalid), counts }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment