botbuilder-core
Version:
Core components for Microsoft Bot Builder. Components in this library can run either in a browser or on the server.
91 lines • 3.02 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.MiddlewareSet = void 0;
/**
* A set of `Middleware` plugins.
*
* @remarks
* The set itself is middleware so you can easily package up a set of middleware that can be composed
* into an adapter with a single `adapter.use(mySet)` call or even into another middleware set using
* `set.use(mySet)`.
*
* ```JavaScript
* const { MiddlewareSet } = require('botbuilder');
*
* const set = new MiddlewareSet();
* set.use(async (context, next) => {
* console.log(`Leading Edge`);
* await next();
* console.log(`Trailing Edge`);
* });
* ```
*/
class MiddlewareSet {
/**
* Creates a new MiddlewareSet instance.
*
* @param {...any} middlewares One or more middleware handlers(s) to register.
*/
constructor(...middlewares) {
this.middleware = [];
this.use(...middlewares);
}
/**
* Processes an incoming activity.
*
* @param context [TurnContext](xref:botbuilder-core.TurnContext) object for this turn.
* @param next Delegate to call to continue the bot middleware pipeline.
* @returns {Promise<void>} A Promise representing the async operation.
*/
onTurn(context, next) {
return this.run(context, next);
}
/**
* Registers middleware handlers(s) with the set.
*
* @remarks This example adds a new piece of middleware to a set:
* ```JavaScript
* set.use(async (context, next) => {
* console.log(`Leading Edge`);
* await next();
* console.log(`Trailing Edge`);
* });
* ```
* @param {...any} middlewares One or more middleware handlers(s) to register.
* @returns The updated middleware set.
*/
use(...middlewares) {
middlewares.forEach((plugin) => {
if (typeof plugin === 'function') {
this.middleware.push(plugin);
}
else if (typeof plugin === 'object' && plugin.onTurn) {
this.middleware.push((context, next) => plugin.onTurn(context, next));
}
else {
throw new Error('MiddlewareSet.use(): invalid plugin type being added.');
}
});
return this;
}
/**
* Executes a set of middleware in series.
*
* @param context Context for the current turn of conversation with the user.
* @param next Function to invoke at the end of the middleware chain.
* @returns A promise that resolves after the handler chain is complete.
*/
run(context, next) {
const runHandlers = ([handler, ...remaining]) => {
try {
return Promise.resolve(handler ? handler(context, () => runHandlers(remaining)) : next());
}
catch (err) {
return Promise.reject(err);
}
};
return runHandlers(this.middleware);
}
}
exports.MiddlewareSet = MiddlewareSet;
//# sourceMappingURL=middlewareSet.js.map
;