Moleculer supports middlewares. It’s same as plugins in other frameworks. The middleware is an Object
with hooks & wrapper functions. It allows to wrap action handlers, event handlers, broker methods and hook lifecycle events.
示例
// awesome.middleware.js |
Wrapping handlers
Some hooks are wrappers. It means that you can wrap the original handler and return a new Function. Wrap hooks are which the first parameter is next
.
Wrap local action handler
const MyDoSomethingMiddleware = { |
Example validator middleware
const MyValidator = { |
The next
is the original handler or the following wrapped handler. The middleware should return either the original handler
or a new wrapped handler. As you can see above, the middleware checks whether the action has a params
property. If yes, it will return a wrapped handler which calls the validator module before calling the original handler
. If the params
property is not defined, it simply returns the original handler
(skip wrapping).
If you don’t call the original
next
in the middleware it will break the request. It can be used in cachers. For example, if it finds the requested data in the cache, it’ll return the cached data instead of calling thenext
.
Example cacher middleware
const MyCacher = { |
The
next()
always returns aPromise
. So you can access to responses and manipulate them, as well.
Decorate core modules (extend functionality)
Middleware functions can be used to add new features to ServiceBroker
or Service
classes.
Decorate broker with a new allCall
method
// moleculer.config.js |
Call the new method in order to call $node.health
on every nodes:
const res = await broker.allCall("$node.health"); |
Hooks
localAction(next, action)
This hook wraps the local action handlers.
// my.middleware.js |
remoteAction(next, action)
This hook wraps the remote action handlers.
// my.middleware.js |
localEvent(next, event)
This hook wraps the local event handlers.
// my.middleware.js |
localMethod(next, method)
This hook wraps service methods.
// my.middleware.js |
createService(next)
This hook wraps the broker.createService
method.
// my.middleware.js |
destroyService(next)
This hook wraps the broker.destroyService
method
// my.middleware.js |
call(next)
This hook wraps the broker.call
method.
// my.middleware.js |
mcall(next)
This hook wraps the broker.mcall
method.
// my.middleware.js |
emit(next)
This hook wraps the broker.emit
method.
// my.middleware.js |
broadcast(next)
This hook wraps the broker.broadcast
method.
// my.middleware.js |
broadcastLocal(next)
This hook wraps the broker.broadcastLocal
method.
// my.middleware.js |
serviceCreated(service)
(sync)
This hook is called after local service creating.
// my.middleware.js |
serviceStarting(service)
(async)
This hook is called before service starting.
// my.middleware.js |
serviceStarted(service)
(async)
This hook is called after service starting.
// my.middleware.js |
serviceStopping(service)
(async)
This hook is called before service stopping.
// my.middleware.js |
serviceStopped(service)
(async)
This hook is called after service stopping.
// my.middleware.js |
registerLocalService(next)
This hook wraps broker’s local service registering method.
// my.middleware.js |
serviceCreating(service, schema)
This hook is called during local service creation (after mixins are applied, so service schema is merged completely).
// my.middleware.js |
transitPublish(next)
This hook is called before sending a communication packet.
// my.middleware.js |
transitMessageHandler(next)
This hook is called before transit receives & parses an incoming message.
// my.middleware.js |
transporterSend(next)
This hook is called after serialization but before the transporter sends a communication packet.
// my.middleware.js |
transporterReceive(next)
This hook is called after transporter received a communication packet but before serialization.
// my.middleware.js |
newLogEntry(type, args, bindings)
(sync)
This hook is called when a new log messages iscreated.
// my.middleware.js |
created(broker)
(async)
This hook is called when broker created.
// my.middleware.js |
starting(broker)
(async)
This hook is called before broker starting.
// my.middleware.js |
started(broker)
(async)
This hook is called after broker starting.
// my.middleware.js |
stopping(broker)
(async)
This hook is called before broker stopping.
// my.middleware.js |
stopped(broker)
(async)
This hook is called after broker stopped.
// my.middleware.js |
Internal middlewares
Many integrated features have been exposed as internal middlewares. These middlewares are loaded by default when broker is created. However, they can be turned off by setting the internalMiddlewares: false
in broker option. In this case you must explicitly specify the required middlewares in the middlewares: []
broker option.
Internal middlewares
Class name | Type | 说明 |
---|---|---|
ActionHook |
Optional | Action hooks handler. Read more |
Validator |
Optional | Parameter validation. Read more |
Bulkhead |
Optional | Bulkhead feature. Read more |
Cacher |
Optional | Cacher middleware. Read more |
ContextTracker |
Optional | Context tracker feature. Read more |
CircuitBreaker |
Optional | Circuit Breaker feature. Read more |
超时 |
Always | Timeout feature. Read more |
Retry |
Always | Retry feature. Read more |
Fallback |
Always | Fallback feature. Read more |
ErrorHandler |
Always | Error handling. |
跟踪 |
Optional | Tracing feature. Read more |
指标 |
Optional | Metrics feature. Read more |
Debounce |
Optional | Debounce feature. Read more |
Throttle |
Optional | Throttle feature. Read more |
Transmit.Encryption |
Optional | Transmission encryption middleware. Read more |
Transmit.Compression |
Optional | Transmission compression middleware. Read more |
Debugging.TransitLogger |
Optional | Transit Logger. Read more |
Debugging.ActionLogger |
Optional | Action logger. Read more |
Access to internal middlewares
const { Bulkhead, Retry } = require("moleculer").Middlewares; |
Transmission Middleware
Encryption
AES encryption middleware protects all inter-services communications that use the transporter module. This middleware uses built-in Node crypto
lib.
// moleculer.config.js |
Compression
Compression middleware reduces the size of the messages that go through the transporter module. This middleware uses built-in Node zlib
lib.
// moleculer.config.js |
Debug Middlewares
Transit Logger
Transit logger middleware allows to easily track the messages that are exchanged between services.
// moleculer.config.js |
Complete option list
Class name | 类型 | 默认设置 | 说明 |
---|---|---|---|
logger |
Object or Function |
null |
Logger class. 更多. |
logLevel |
String |
info |
Log level for built-in console logger. 更多. |
logPacketData |
Boolean |
false |
Logs packet parameters |
folder |
Object |
null |
Folder where logs will be written |
extension |
String |
.json |
File extension of log file |
color.receive |
String |
grey |
Supports all Chalk colors |
color.send |
String |
grey |
Supports all Chalk colors |
packetFilter |
Array<String> |
HEARTBEAT |
Type of packets to skip |
Action Logger
Action Logger middleware tracks “how” service actions were executed.
// moleculer.config.js |
Complete option list
Class name | 类型 | 默认设置 | 说明 |
---|---|---|---|
logger |
Object or Function |
null |
Logger class. 更多. |
logLevel |
String |
info |
Log level for built-in console logger. 更多. |
logParams |
Boolean |
false |
Logs request parameters |
logMeta |
Boolean |
false |
Logs meta parameters |
folder |
String |
null |
Path do folder where logs will be written |
extension |
String |
.json |
File extension of log file |
color.request |
String |
yellow |
Supports all Chalk colors |
color.response |
String |
cyan |
Supports all Chalk colors |
colors.error |
String |
red |
Supports all Chalk colors |
whitelist |
Array<String> |
["**"] |
Actions to log. Uses the same whitelisting mechanism as in API Gateway. |
Event Execution Rate
Throttle
Throttling is a straightforward reduction of the trigger rate. It will cause the event listener to ignore some portion of the events while still firing the listeners at a constant (but reduced) rate. Same functionality as lodash’s _.throttle
. For more info about throttling check this article.
//my.service.js |
Debounce
Unlike throttling, debouncing is a technique of keeping the trigger rate at exactly 0 until a period of calm, and then triggering the listener exactly once. Same functionality as lodash’s _.debounce
. For more info about debouncing check this article.
//my.service.js |
Loading & Extending
If you want to use the built-in middlewares use their names in middlewares[]
broker option. Also, the Middlewares
can be easily extended with custom functions.
Load middleware by name
// moleculer.config.js |