Skip to content

Instantly share code, notes, and snippets.

@conorhastings
Created December 24, 2017 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conorhastings/825b07a354471fd177e2953546967a5e to your computer and use it in GitHub Desktop.
Save conorhastings/825b07a354471fd177e2953546967a5e to your computer and use it in GitHub Desktop.
subscriable request
export default function subscribableRequest({ baseUrl }) {
let subscriptions = {};
return {
fetch: ({ endpoint, ...rest }) => (
fetch(`${baseUrl}/${endpoint}`, ...rest)
.then(res => res.json())
.then(res => {
subscriptions[endpoint] &&
subscriptions[endpoint].forEach(sub => sub(res));
return res;
});
),
subscribe({ endpoint, fn }) {
subscriptions[endpoint] = (subscriptions[endpoint] || []).concat(fn);
return function unsubscribe() {
subscriptions = subscriptions.filter(sub => sub !== fn);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment