Moleculer supports middlewares. The middleware is an Object with hooks & wrapper functions. Wrap action handlers, event handlers, broker methods and hook lifecycle events.
All available methods:
const MyCustomMiddleware = { |
Wrapping handlers
Some hooks are wrappers. It means you must wrap the original handler and return a new Function.
Wrap hooks where 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, we check whether the action has a params props. If yes, we’ll return a wrapped handler which calls the validator module before calling the original handler.
If the params property is not defined, we will return the original handler (skipped wrapping).
If you don’t call the original
nextin 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
nextalways returns aPromise. So you can access to responses and manipulate them, as well.
Decorate core modules (extend functionality)
With other hooks are help you to add new features to ServiceBroker & Service.
Decorate broker with a new allCall method
const broker = new ServiceBroker({ |
Internal middlewares
Many integrated features have been exposed to internal middlewares. These middlewares are loaded by default when broker is created. It can be turned off with the internalMiddlewares: false in broker option. In this case you must add what you need in the middlewares: [] broker option.
Internal middlewares
| Class name | Type | Description |
|---|---|---|
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 |
Timeout |
Always | Timeout feature. Read more |
Retry |
Always | Retry feature. Read more |
Fallback |
Always | Fallback feature. Read more |
ErrorHandler |
Always | Error handling. |
Metrics |
Optional | Metrics feature. Read more |
Access to internal middlewares
const { Bulkhead, Retry } = require("moleculer").Middlewares; |