Skip to content

A utility for composing concurrent operations, yet allowing state to be merged in series.

License

Notifications You must be signed in to change notification settings

mylesj/immer-compose

Repository files navigation

NPM Package Version GitHub Repository Changelog GitHub Workflow Status (main) Test Coverage

immer-compose

A utility for composing concurrent operations, yet allowing state to be merged in series.

Install / Prerequisites

Immer is a required peer-dependency.

npm install immer immer-compose

Motivation

I was looking for a neat way to merge async updates to an arbitrary document (JSON Schema) in a sequential order - in my use-case the updates may only be loosely related and I wanted to separate concerns by expressing them as middleware, e.g.

const pipeline = compose(middlewareOne, middlewareTwo, middleWareThree)
const newState = pipeline(initialState)

Yes it's another micro-library... but I found this idea somewhat complex to think through and felt that it warranted an isolated module - no doubt there'll be alternatives, but I couldn't find what I was looking for - with immutability in mind.

Usage

The functions compose and composeWithPatches are exposed mirroring the producer functions provided by immer. Note that to use patches, it is still required that you import enablePatches from immer - this module assumes nothing about which version you are using.

Compose arguments are higher-order functions that can execute any asynchronous task and in-turn return an immer recipe - where each recipe will consume a draft of the previous state in the chain.

const higherOrderRecipe = async (initialState) => {
    const data = await task()
    return (draftState) => {
        draftState.foo = 'bar'
    }
}

Additionally, any other input passed to the composed function will be passed through.

const higherOrderRecipe = async (initial, a, b, c) => (draft) => {}
const pipeline = compose(higherOrderRecipe /* [, 0..*] */)
const newState = pipeline(state, 1, 2, 3)

Experimental  ⚠️

const experimental = async () => async () => {}

If a recipe is returned as an async function, the compose function will prioritise the order of the synchronous recipes before processing the remaining tasks on a first-come first-serve basis. Effectively allowing middleware to self-determine whether to keep a slot in the queue or go last.

The implementation should be reliable in modern environments however, should also be considered experimental as I don't know where I want to take this idea yet and also don't know how much utility it really affords - I was just playing around.

This behaviour is reliant on native async functions and won't work with regular functions returning promises - due to this, it also will not work if you are targeting es5 through code transpilers like Babel.

About

A utility for composing concurrent operations, yet allowing state to be merged in series.

Topics

Resources

License

Stars

Watchers

Forks

Languages