UNPKG

2.56 kBJavaScriptView Raw
1"use strict";
2/*
3 * Copyright © 2020 Atomist, Inc.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17Object.defineProperty(exports, "__esModule", { value: true });
18const function_1 = require("./function");
19const log_1 = require("./log");
20const payload_1 = require("./payload");
21const util_1 = require("./util");
22const HandlerRegistry = {
23 events: {},
24 commands: {},
25};
26/**
27 * Register a command handler with a certain name
28 */
29function registerCommand(name, loader) {
30 HandlerRegistry.commands[name] = loader;
31}
32exports.registerCommand = registerCommand;
33/**
34 * Register a event handler with a certain name
35 */
36function registerEvent(name, loader) {
37 HandlerRegistry.events[name] = loader;
38}
39exports.registerEvent = registerEvent;
40exports.bundle = async (pubSubEvent, context) => {
41 const attributes = Object.assign(Object.assign({}, (pubSubEvent.attributes || {})), { eventId: context.eventId });
42 log_1.debug(`atm:attributes=${JSON.stringify(attributes)}`);
43 const payload = JSON.parse(Buffer.from(pubSubEvent.data, "base64").toString());
44 log_1.info(`Incoming pub/sub message: ${JSON.stringify(payload, util_1.replacer)}`);
45 if (payload_1.isEventIncoming(payload)) {
46 return function_1.processEvent(payload, context, async () => {
47 const loader = HandlerRegistry.events[payload.extensions.operationName];
48 if (loader) {
49 return loader();
50 }
51 else {
52 throw new Error(`Event handler with name '${payload.extensions.operationName}' not registered`);
53 }
54 });
55 }
56 else if (payload_1.isCommandIncoming(payload)) {
57 return function_1.processCommand(payload, context, async () => {
58 const loader = HandlerRegistry.commands[payload.command];
59 if (loader) {
60 return loader();
61 }
62 else {
63 throw new Error(`Command handler with name '${payload.command}' not registered`);
64 }
65 });
66 }
67};
68//# sourceMappingURL=bundle.js.map
\No newline at end of file