Async Middleware
The Async Middleware is built-in middleware that gives you capability to defer the handling to an consumer to achieve real asynchronousity. It’s only available for CommandBus and EventBus
How to use it
As for any Middleware, you can use it by adding it to the bus
instance.
const commandBus = createCommandBus<CommandHandlerRegistry>();commandBus.useAsyncMiddleware({ consume: false, // KEY POINT produce: async (envelope) => { // use your favorite queue system here console.log('Generic Push to Queue', envelope); }, async: true,// default is true intents: { createUser: { async: true, produce: async (envelope) => { // use your favorite queue system here console.log('createUser Push to Queue', envelope); }, }, },});
Remember built-in middlewares are intent aware, therefore you can customize the behavior per intent using the key
intents
.
Next, you need to have a consumer that will consume it. The way to do that with Missive.js is to create another bus with this middlware with consume: true
.
commandBus.useAsyncMiddleware({ consume: true, // KEY POINT});
The worker script that consumes the queue can dispatch the message it receives directly to the dispatch method:
// Consumer scriptonMessage: async (message) => { const envelope = JSON.parse(message); await commandBus.dispatch(intent);}
Explanation
The flow is the following:
-
Your application (web node for instance) will have a bus on which this middleware is added with
consume: false
. -
When you dispatch an intent, the middleware will push the intent to the queue system (via the
produce
method that you provide) instead of handling it. -
You have another application (worker node for instance) that will have a bus on which this middleware is added with
consume: true
. -
This worker will consume the intent from the queue system and handle it.
Added Stamps
The Async Middleware is going to add:
-
type AsyncStamp = Stamp<undefined, 'missive:async'>;
When the intent is pushed to the queue.
-
type ReprocessedStamp = Stamp<{ stamps: Stamp[] }, 'missive:reprocessed'>;
When the envelope is dispatched.
Going further
Missive.js. MIT License.
Powered by Astro Starlight.
Inspired by Symfony Messenger