You can define middleware functions by registering them in the dispatcher (using a name) and use them in your
application's action definition. Your middleware functions should contain simple functionality and alter the incoming
intentObj
by overriding input data, or pass data from one middleware to the next, by using the data()
function of an intent.
The core middleware class is under thorin.Middleware
and can be extended by other thorin components, using the
pattern below:
'use strict';
const CoreMiddleware = thorin.Middleware;
thorin.Middleware = class ThorinMiddleware extends CoreMiddleware {
constructor(name) {
super(name);
// your custom functionality
}
}
use("middlewareName")
.
A middleware can also register an anonymous handler using use((intentObj, next, opt) => {})
, that will receive the
incoming intent object as well as any options that were passed by higher dependencies. (see below)
_runStack
function, it will execute the internal middleware call stack in the
chronological order they were defined. This is usually called by the dispatcher.
'use strict';
const dispatcher = thorin.dispatcher;
// Register our middleware.
dispatcher
.addMiddleware('mid.one')
.input({
name: dispatcher.validate('STRING') // it will fail with a generic error if no name is provided
})
.use((intentObj, next, opt) => {
log.info(`Should process action ${intentObj.action} using middleware options `, opt);
if(opt.nickname) {
intentObj.data('nick', 'A silly object name');
}
next();
});
// Add a separate middleware
dispatcher
.addMiddleware('mid.two')
.use('mid.one', {
nickname: true
})
.use((intentObj, next) => {
log.info(`Got nickname: ${intentObj.data('nick')}`);
next();
});
// Add an action that will use the second middleware.
dispatcher
.addAction('home.example')
.use('mid.two')
.use((intentObj, next) => {
log.info(`Done`);
intentObj.result({
nick: intentObj.data('nick')
}).send();
});
You can always create a new issue on GitHub or contact one of the core founders by chat.