@kitmi/jacaranda
Version:
JavaScript application framework
82 lines (81 loc) • 2.74 kB
JavaScript
/**
* Response action as middleware
* @module Middleware_Action
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return _default;
}
});
const _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
const _types = require("@kitmi/types");
const _utils = require("@kitmi/utils");
const _loadModuleFrom_ = require("../helpers/loadModuleFrom_");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
/**
* Action middleware creator
* @param {string} controllerAction
* @param {Routable} app
*/ const action = async (controllerAction, app)=>{
app.log('verbose', 'Loading action: ', {
action: controllerAction
});
if (typeof controllerAction !== 'string') {
throw new _types.InvalidConfiguration('Invalid action syntax.', app);
}
let pos = controllerAction.lastIndexOf('.');
if (pos < 0) {
throw new _types.InvalidConfiguration(`Unrecognized controller & action syntax: ${controllerAction}.`, app);
}
let controller = controllerAction.substring(0, pos);
let action = controllerAction.substring(pos + 1);
let ctrl = await (0, _loadModuleFrom_.tryLoadFrom_)(app, 'Controller', {
registry: {
name: controller,
path: 'controllers.actions'
},
project: {
name: controller,
path: _nodepath.default.join(app.sourcePath, 'actions')
}
});
let isController = false;
if (typeof ctrl === 'function') {
isController = true;
let _ctrl = (0, _utils.get)(app.__controllerCache, controller);
if (_ctrl == null) {
if (!app.__controllerCache) {
app.__controllerCache = {};
}
_ctrl = new ctrl(app);
(0, _utils.set)(app.__controllerCache, controller, _ctrl);
}
ctrl = _ctrl;
}
// todo: path support
let actioner = ctrl[action];
if (isController) {
actioner = actioner.bind(ctrl);
}
if (Array.isArray(actioner)) {
let actionFunction = actioner.concat().pop();
if (typeof actionFunction !== 'function') {
throw new _types.InvalidConfiguration(`${controllerAction} does not contain a valid action in returned middleware chain.`, app);
}
return actioner.concat(actionFunction);
}
if (typeof actioner !== 'function') {
throw new _types.InvalidConfiguration(`${controllerAction} is not a valid action.`, app);
}
return actioner;
};
const _default = action;
//# sourceMappingURL=action.js.map