-
Notifications
You must be signed in to change notification settings - Fork 0
/
MicroService.js
81 lines (61 loc) · 2.41 KB
/
MicroService.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
export function MicroService(Settings) {
const Actions = new Map();
//Crear las acciones correspondientes
Object.keys(Settings.actions).forEach(aname => {
Actions.set(aname, CreateAction(Settings.actions[aname], Settings))
});
function getAction(actionName) {
if(!Actions.get(actionName)) {
throw new Error(`Accion no definida ${actionName}`);
}
return Actions.get(actionName);
}
async function invoke (req, res) {
const actionName = req.params.actionName;
try {
const action = getAction(actionName);
const actionContext = {isMiddleware: true, req, res, params:{}, input:req.body};
const result = await action.execute(actionContext);
res.send({result});
} catch (e) {
res.status(500)
res.send({err : e.message})
}
}
return {invoke, getAction}
}
function CreateAction(ActionDescr, Settings) {
const actionArguments = ActionDescr;
const actionFunction = ActionDescr.pop();
async function BuildArguments(context) {
return asyncMap(actionArguments, async (argName) => await ProcessArg(argName, context.input, context));
}
async function ProcessArg(argName, input, context) {
const argDescr = Settings.params[argName];
if(!argDescr) throw new Error(`Argumento no definido (${argName}).`);
//Se convierte el procesador de argumentos a un array en el caso de que no lo sea
const argumentDescriptor = Array.isArray(argDescr) || [argDescr]
//Se procesa el parámetro de forma secuencial
let value = input[argName];
await asyncMap(argumentDescriptor, async (argdesc) => {
value = await argdesc.apply(context, [value, input]);
});
//Se asigna el valor final al contexto
context.params[argName] = value;
//Se retorna el valor
return context.params[argName]
}
async function execute(context) {
// Se procesan uno a uno los argumentos
const localArguments = await BuildArguments(context);
return actionFunction.apply(context, localArguments);
};
return {execute};
}
async function asyncMap(array, actionFn) {
const returnArray = [];
for(const [index, element] of array.entries()) {
returnArray.push(await actionFn(element, index));
}
return returnArray;
}