@micro.ts/core
Version:
Microservice framework with Typescript
109 lines (108 loc) • 3.23 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbstractBroker = void 0;
const errors_1 = require("../errors");
class AbstractBroker {
/**
* If provided absolute config, the construct method is called immediately
* @param absoluteConfig
*/
constructor(absoluteConfig) {
this.timeout = 0;
this.registeredRoutes = new Map();
this.actionToRouteMapper = (route, action, pairs) => {
const method = action.request.method;
if (method) {
const filtered = pairs.filter((x) => {
return x.def.method === method;
});
if (filtered.length) {
return filtered[0].handler;
}
}
return pairs[0].handler;
};
if (absoluteConfig) {
this.setAbsoluteConfig(absoluteConfig);
}
}
get config() {
if (this.absoluteConfig) {
return this.absoluteConfig;
}
if (this.appConfiguration && this.configResolver) {
return this.configResolver(this.appConfiguration);
}
return {};
}
setConfigResolver(cfg, resolver) {
this.appConfiguration = cfg;
this.configResolver = resolver;
this.construct();
}
setAbsoluteConfig(config) {
this.absoluteConfig = config;
this.construct();
}
setConnectionErrorHandler(handler) {
this.connectionErrorHandler = handler;
}
setRequestMapper(requestMapper) {
this.requestMapper = requestMapper;
}
setRouteMapper(routeMapper) {
this.routeMapper = routeMapper;
}
setActionToHandlerMapper(mapper) {
this.actionToRouteMapper = mapper;
}
getHandler(route, action) {
let allHandlers = this.registeredRoutes.get(route);
allHandlers = allHandlers || [];
if (allHandlers.length === 0) {
throw new errors_1.NotFound('Not found');
}
return this.actionToRouteMapper(route, action, allHandlers);
}
addRoute(def, handler) {
const route = this.routeMapper(def);
let registered = this.registeredRoutes.get(route);
if (!registered) {
registered = [];
}
registered.push({ def, handler });
this.registeredRoutes.set(route, registered);
return route;
}
extractParamNames(path, separator = '/') {
const spl = path.split(separator);
return spl.map((x) => {
const value = {
name: x,
param: false,
};
if (x.length > 0 && x[0] === ':') {
value.name = x.substring(1);
value.param = true;
}
return value;
});
}
getDefaultTimeout() {
return this.timeout;
}
setDefaultTimeout(val) {
if (val > 0) {
this.timeout = val;
}
}
handleConnectionError(e) {
if (this.connectionErrorHandler) {
this.connectionErrorHandler(this, e);
}
else {
throw e;
}
}
}
exports.AbstractBroker = AbstractBroker;