Implementing the Middleware to Process Messages
Learn how to implement and use the ZeroMQ middleware framework.
We'll cover the following...
Now that we’ve implemented our Middleware Manager, we can create our first pair of middleware functions to demonstrate how to process inbound and outbound messages. As we said, one of the goals of our middleware infrastructure is to have a filter that serializes and deserializes JSON messages. So, let’s create a new middleware to take care of this. In a new jsonMiddleware.js
named module, let’s include the following code:
export const jsonMiddleware = function () {return {inbound (message) {return JSON.parse(message.toString())},outbound (message) {return Buffer.from(JSON.stringify(message))}}}
The inbound part of our middleware deserializes the message received as input, while the outbound part serializes the data into a string, which is then converted into a buffer.
In a similar way, we can implement a pair of middleware functions in a zlibMiddleware.js
named file, to inflate/deflate the message using the zlib
core module.
import { inflateRaw, deflateRaw } from 'zlib'import { promisify } from 'util'const inflateRawAsync = promisify(inflateRaw)const deflateRawAsync = promisify(deflateRaw)export const zlibMiddleware = function () {return {inbound (message) {return inflateRawAsync(Buffer.from(message))},outbound (message) {return deflateRawAsync(message)}}}
Compared to the JSON middleware, our zlib
middleware functions are asynchronous and ...