UNPKG

@ebonydevcopy/framework

Version:

A module-based NodeJS chatbot framework.

93 lines 2.73 kB
"use strict"; /** * ebony-framework * * @module utilities/actions * @author Christos Panagiotakopoulos <chrispanag@gmail.com> * @copyright Copyright(c) 2020 Christos Panagiotakopoulos * @license MIT * */ Object.defineProperty(exports, "__esModule", { value: true }); /** * The Actions Class */ class Actions { constructor(preMiddlewares = [], postMiddlewares = []) { this.actions = {}; this.preMiddlewares = []; this.postMiddlewares = []; this.preMiddlewares = preMiddlewares; this.postMiddlewares = postMiddlewares; } addMiddleware(type, middleware) { switch (type) { case 'pre': this.preMiddlewares.push(middleware); return; case 'post': this.postMiddlewares.push(middleware); return; } } addMiddlewares(type, middlewares) { switch (type) { case 'pre': this.preMiddlewares = this.preMiddlewares.concat(middlewares); return; case 'post': this.postMiddlewares = this.postMiddlewares.concat(middlewares); return; } } /** * Adds actions to the bot */ importActions(actions = {}) { this.actions = Object.assign(this.actions, actions); } nextFactory(type, actionName, user, params) { const actions = this.actions; const middlewares = type === 'pre' ? this.preMiddlewares : this.postMiddlewares; let i = 0; const next = async () => { try { if (middlewares.length <= i) { if (type === 'pre') { await actions[actionName](user, ...params); } return; } i = i + 1; await middlewares[i - 1](actionName, user, params, next); return; } catch (err) { throw err; } }; return next; } /** * Executes an action */ async exec(actionName, user, ...params) { if (actionName in this.actions) { const preNext = this.nextFactory('pre', actionName, user, params); const postNext = this.nextFactory('post', actionName, user, params); try { await preNext(); } catch (err) { throw err; } finally { postNext(); } return; } throw new Error(`[Error] Action with name: ${actionName} doesn't exist!`); } } exports.default = Actions; //# sourceMappingURL=actions.js.map