1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const _ = require("lodash");
|
4 | exports.NoEventHandlersError = "NO_EVENT_HANDLERS";
|
5 | function noEventHandlersWereFound(result) {
|
6 | return result.code !== 0 && !!result.message && result.message.startsWith(exports.NoEventHandlersError);
|
7 | }
|
8 | exports.noEventHandlersWereFound = noEventHandlersWereFound;
|
9 |
|
10 |
|
11 |
|
12 | class AbstractAutomationServer {
|
13 | invokeCommand(payload, ctx) {
|
14 | const h = this.validateCommandInvocation(payload);
|
15 | return this.invokeCommandHandler(payload, h, ctx);
|
16 | }
|
17 | onEvent(payload, ctx) {
|
18 | const h = this.automations.events.filter(eh => eh.subscriptionName === payload.extensions.operationName);
|
19 | if (!h || h.length === 0) {
|
20 | throw new Error(`${exports.NoEventHandlersError}: No event handler with name '${payload.extensions.operationName}'` +
|
21 | `: Known event handlers are '${this.automations.events.map(e => e.name)}'`);
|
22 | }
|
23 | else {
|
24 | return Promise.all(h.map(eh => this.invokeEventHandler(payload, eh, ctx)));
|
25 | }
|
26 | }
|
27 | validateCommandInvocation(payload) {
|
28 | const handler = this.automations.commands.find(h => h.name === payload.name);
|
29 | if (!handler) {
|
30 | throw new Error(`No command handler with name '${payload.name}'` +
|
31 | `: Known command handlers are '${this.automations.commands.map(c => c.name)}'`);
|
32 | }
|
33 | handler.parameters.forEach(p => {
|
34 | const payloadValue = payload.args ?
|
35 | payload.args.find(a => a.name === p.name) : undefined;
|
36 | if (!payloadValue || _.isNil(payloadValue.value)) {
|
37 | if (p.required && p.default_value === undefined) {
|
38 | throw new Error(`Parameter '${p.name}' required but missing in invocation to '${handler.name}'`);
|
39 | }
|
40 | }
|
41 | else {
|
42 |
|
43 | if (p.pattern && payloadValue.value.toString().match(new RegExp(p.pattern)) === null) {
|
44 | throw new Error(`Parameter '${p.name}' value of '${payloadValue.value}'` +
|
45 | ` invalid in invocation to '${handler.name}' with pattern '${p.pattern}'`);
|
46 | }
|
47 | }
|
48 | });
|
49 | return handler;
|
50 | }
|
51 | }
|
52 | exports.AbstractAutomationServer = AbstractAutomationServer;
|
53 |
|
\ | No newline at end of file |