UNPKG

2.15 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3/**
4 * Support for implementing an automation server.
5 */
6class AbstractAutomationServer {
7 invokeCommand(payload, ctx) {
8 const h = this.validateCommandInvocation(payload);
9 return this.invokeCommandHandler(payload, h, ctx);
10 }
11 onEvent(payload, ctx) {
12 const h = this.automations.events.filter(eh => eh.subscriptionName === payload.extensions.operationName);
13 if (!h || h.length === 0) {
14 throw new Error(`No event handler with name '${payload.extensions.operationName}'` +
15 `: Known event handlers are '${this.automations.events.map(e => e.name)}'`);
16 }
17 else {
18 return Promise.all(h.map(eh => this.invokeEventHandler(payload, eh, ctx)));
19 }
20 }
21 validateCommandInvocation(payload) {
22 const handler = this.automations.commands.find(h => h.name === payload.name);
23 if (!handler) {
24 throw new Error(`No command handler with name '${payload.name}'` +
25 `: Known command handlers are '${this.automations.commands.map(c => c.name)}'`);
26 }
27 handler.parameters.forEach(p => {
28 const payloadValue = payload.args ?
29 payload.args.find(a => a.name === p.name) : undefined;
30 if (!payloadValue || !payloadValue.value) {
31 if (p.required && p.default_value === undefined) {
32 throw new Error(`Parameter '${p.name}' required but missing in invocation to '${handler.name}'`);
33 }
34 }
35 else {
36 // We have a parameter. Validate it
37 if (p.pattern && payloadValue.value.toString().match(new RegExp(p.pattern)) === null) {
38 throw new Error(`Parameter '${p.name}' value of '${payloadValue.value}'` +
39 ` invalid in invocation to '${handler.name}' with pattern '${p.pattern}'`);
40 }
41 }
42 });
43 return handler;
44 }
45}
46exports.AbstractAutomationServer = AbstractAutomationServer;
47//# sourceMappingURL=AbstractAutomationServer.js.map
\No newline at end of file