js-promise-middleware
A middleware wrapper for promises that simplifies side effect management.
The problem
You have a reactive application and are too lazy to learn how to use observables?
Example
Import it
import PromiseMiddleware from 'js-promise-middleware'
import { cache, dedupe } from 'js-promise-middleware/middleware'
Declare your fetcher
const fetchUser = id => fetch(`/users/${id}`).then(res => res.json())
const UserFetcher = new PromiseMiddleware(fetchUser)
const idGetter = id => id
cache(idGetter)(UserFetcher)
dedupe(idGetter)(UserFetcher)
compose(
cache,
dedupe
)(UserFetcher)
export default UserFetcher
Use it
import UserFetcher from 'fetchers/User'
const unsubscribe = UserFetcher.onSuccess(onUserFetchSuccess)
function onUserFetchSuccess({ res, args }) {
console.log(`Got the user with the id ${idGetter(...args)}!`, res)
}
UserFetcher.request(1)
UserFetcher.request(1)
UserFetcher.request(2)
UserFetcher.request(2)
unsubscribe()
Publishing
To publish this as an npm package, use yarn publish-package
rather than the usual yarn publish
.
This runs a custom npm script that builds the js-promise-middleware, moves the package.json file to the es
directory and publishes from there.
It allows consumers of this npm package to use your dependency by writing
import someModule from 'js-promise-middleware/someModule'
rather than
import someModule from 'js-promise-middleware/es/someModule'