WICG / pending-beacon

A better beaconing API
Other
43 stars 9 forks source link

consider reducer API for updating #33

Open fergald opened 2 years ago

fergald commented 2 years ago

Suggestion from @dominiccooney to consider an API for updating data that is more stream-like. Hopefully this captures it accurately

beacon.updateData(reducer, initialValue)

where reducer(currentValue) returns the new value and if the beacon has already been sent, initialValue is passed in.

Examples:

Replace every time

let newValue = ...;
beacon.updateData(() => {return newValue});

Accumulate data

let diffSinceLastTime = ...;
beacon.updateData((oldValue) => {return oldValue + diffSinceLastTime}, 0);

// cc @nicjansma @cliffcrocker @andydavies @philipwalton @yoavweiss

philipwalton commented 2 years ago

What about if the API accepted a WritableStream instance?

I'm not sure if that would be possible with this API, but if so, it seems like that could potentially make it more compatible with other streaming use cases.

mingyc commented 2 years ago

Some previous related discussion around the API shape: https://github.com/WICG/unload-beacon/issues/9#issuecomment-1183665703

nicjansma commented 2 years ago

This could be useful so the application doesn't need to maintain a duplicate payload state for what it's hoping to send in the beacon.

With today's API shape, if someone wanted to beacon a log of events, they'd need to:

var events = [];

// on new data
events.push({...}); // append to your events list
beacon.setData(events); // replace current beacon payload list with list+1

With updateData you wouldn't need a local (duplicate) copy of the data:

// on new data
beacon.updateData((events) => { return events.push({...}) }, []); // append to existing