Created
December 24, 2017 17:01
-
-
Save conorhastings/825b07a354471fd177e2953546967a5e to your computer and use it in GitHub Desktop.
subscriable request
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
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