@yopdev/dev-server 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ export declare function assertNotUndefined<T>(value: T | undefined, message?: string): T;
package/dist/assert.js ADDED
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertNotUndefined = void 0;
4
+ function assertNotUndefined(value, message) {
5
+ if (message === void 0) { message = 'value is undefined'; }
6
+ if (value === undefined)
7
+ throw new Error(message);
8
+ return value;
9
+ }
10
+ exports.assertNotUndefined = assertNotUndefined;
@@ -0,0 +1,34 @@
1
+ import { Sqs } from "./sqs";
2
+ import { Sns } from "./sns";
3
+ import { DynamoDb } from "./dynamodb";
4
+ import { StartedNetwork } from "testcontainers";
5
+ export type Config = {
6
+ servicesPort: number;
7
+ localStackDockerImage: string | undefined;
8
+ useRandomPorts: boolean;
9
+ localStateBindMount: string | undefined;
10
+ queueName: string;
11
+ topicName: string;
12
+ table: string;
13
+ };
14
+ export type AwsConfig = {
15
+ region: string;
16
+ endpoint: string;
17
+ credentials: {
18
+ accessKeyId: string;
19
+ secretAccessKey: string;
20
+ };
21
+ };
22
+ export type DevServerConfig = {
23
+ raw: AwsConfig;
24
+ network: StartedNetwork;
25
+ sqs: Sqs;
26
+ sns: Sns;
27
+ dynamo: DynamoDb;
28
+ table: string;
29
+ topic: {
30
+ arn: string;
31
+ name: string;
32
+ };
33
+ queue: string;
34
+ };
package/dist/config.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,12 @@
1
+ import { Config } from "./config";
2
+ import { Lifecycle, Service } from "./services";
3
+ export declare class DevServer implements Lifecycle<DevServer> {
4
+ readonly name: string;
5
+ private readonly config;
6
+ private readonly service;
7
+ private LOGGER;
8
+ private localStack;
9
+ constructor(name: string, config: Config, service: Service<any>);
10
+ start: () => Promise<this>;
11
+ stop: () => Promise<void>;
12
+ }
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DevServer = void 0;
4
+ var testcontainers_1 = require("testcontainers");
5
+ var localstack_1 = require("./localstack");
6
+ var sqs_1 = require("./sqs");
7
+ var dynamodb_1 = require("./dynamodb");
8
+ var logging_1 = require("@yopdev/logging");
9
+ var sns_1 = require("./sns");
10
+ var DevServer = /** @class */ (function () {
11
+ function DevServer(name, config, service) {
12
+ var _this = this;
13
+ this.name = name;
14
+ this.config = config;
15
+ this.service = service;
16
+ this.start = function () {
17
+ return Promise.resolve(new testcontainers_1.Network(new testcontainers_1.RandomUuid()).start())
18
+ .then(function (network) { return ({
19
+ localStack: _this.localStack = new localstack_1.LocalStack(_this.config, network),
20
+ network: network
21
+ }); })
22
+ .then(function (infra) { return infra.localStack.start().then(function (config) { return ({
23
+ aws: config,
24
+ network: infra.network
25
+ }); }); })
26
+ .then(function (infra) { return ({
27
+ raw: infra.aws,
28
+ network: infra.network,
29
+ sqs: new sqs_1.Sqs(infra.aws),
30
+ sns: new sns_1.Sns(infra.aws),
31
+ dynamo: new dynamodb_1.DynamoDb(infra.aws),
32
+ table: _this.config.table,
33
+ topic: {
34
+ arn: "arn:aws:sns:us-east-1:000000000000:".concat(_this.config.topicName),
35
+ name: _this.config.topicName,
36
+ },
37
+ queue: _this.config.queueName,
38
+ }); })
39
+ .then(function (config) { _this.LOGGER.debug('starting. config is %o', config); return config; })
40
+ .then(function (aws) { return _this.service.start(aws); })
41
+ .then(function () { return _this.LOGGER.info('started'); })
42
+ .then(function () { return _this; });
43
+ };
44
+ this.stop = function () { return _this.service.stop()
45
+ .then(function () { var _a; return (_a = _this.localStack) === null || _a === void 0 ? void 0 : _a.stop(); })
46
+ .then(function () { return _this.LOGGER.info('stopped'); }); };
47
+ this.LOGGER = logging_1.LoggerFactory.create("DEVSERVER[".concat(name, "]"));
48
+ }
49
+ return DevServer;
50
+ }());
51
+ exports.DevServer = DevServer;
@@ -0,0 +1,11 @@
1
+ import { CreateTableCommand } from "@aws-sdk/client-dynamodb";
2
+ import { AwsConfig } from "./config";
3
+ import { Service, ServiceConfig } from "./services";
4
+ export declare const newDynamoDbTable: (name: string, config: {
5
+ command: CreateTableCommand;
6
+ }, service: ServiceConfig<string>) => Service<string>;
7
+ export declare class DynamoDb {
8
+ private readonly dynamo;
9
+ constructor(config: AwsConfig);
10
+ createTable: (factory: CreateTableCommand) => Promise<import("@aws-sdk/client-dynamodb").CreateTableCommandOutput>;
11
+ }
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.DynamoDb = exports.newDynamoDbTable = void 0;
40
+ var client_dynamodb_1 = require("@aws-sdk/client-dynamodb");
41
+ var logging_1 = require("@yopdev/logging");
42
+ var services_1 = require("./services");
43
+ var newDynamoDbTable = function (name, config, service) { return new services_1.Service(new DynamoDbTableCreator(name, config.command), service); };
44
+ exports.newDynamoDbTable = newDynamoDbTable;
45
+ var DynamoDbTableCreator = /** @class */ (function () {
46
+ function DynamoDbTableCreator(name, command) {
47
+ var _this = this;
48
+ this.name = name;
49
+ this.command = command;
50
+ this.start = function (config) { return __awaiter(_this, void 0, void 0, function () {
51
+ var _this = this;
52
+ return __generator(this, function (_a) {
53
+ return [2 /*return*/, config.dynamo.createTable(this.command)
54
+ .then(function () { return _this.LOGGER.info('created'); })
55
+ .then(function () { return _this.name; })];
56
+ });
57
+ }); };
58
+ this.stop = function () { return Promise.resolve()
59
+ .then(function () { return _this.LOGGER.info('stopped'); }); };
60
+ this.LOGGER = logging_1.LoggerFactory.create("TABLE[".concat(name, "]"));
61
+ }
62
+ return DynamoDbTableCreator;
63
+ }());
64
+ var LOGGER = logging_1.LoggerFactory.create('DYNAMODB');
65
+ var DynamoDb = /** @class */ (function () {
66
+ function DynamoDb(config) {
67
+ var _this = this;
68
+ this.createTable = function (factory) { return __awaiter(_this, void 0, void 0, function () {
69
+ return __generator(this, function (_a) {
70
+ return [2 /*return*/, this.dynamo
71
+ .send(factory) //
72
+ .then(function (table) { var _a; LOGGER.info('table created %s', (_a = table.TableDescription) === null || _a === void 0 ? void 0 : _a.TableName); return table; })
73
+ .catch(function (reason) {
74
+ LOGGER.error('failed to create table');
75
+ if (reason.name !== 'ResourceInUseException')
76
+ return Promise.reject(reason);
77
+ })];
78
+ });
79
+ }); };
80
+ this.dynamo = new client_dynamodb_1.DynamoDBClient(config);
81
+ LOGGER.debug('initialized');
82
+ }
83
+ return DynamoDb;
84
+ }());
85
+ exports.DynamoDb = DynamoDb;
@@ -0,0 +1,26 @@
1
+ import { SQSEvent } from 'aws-lambda';
2
+ import { Lifecycle, Service, ServiceConfig } from './services';
3
+ import { DevServerConfig } from './config';
4
+ export declare const newEventsProxy: (name: string, config: {
5
+ handlers: EventHandler[];
6
+ }, service: ServiceConfig<EventsProxy>) => Service<EventsProxy>;
7
+ declare class EventsProxy implements Lifecycle<EventsProxy> {
8
+ readonly name: string;
9
+ private readonly handlers;
10
+ private LOGGER;
11
+ private consumer;
12
+ private readonly pollingFrequency;
13
+ private stopped;
14
+ constructor(name: string, handlers: EventHandler[]);
15
+ start: (config: DevServerConfig) => Promise<this>;
16
+ private queueConnectedToTopic;
17
+ private startEventsConsumer;
18
+ private extractErrorMessage;
19
+ private onEachMessage;
20
+ stop: () => Promise<void>;
21
+ }
22
+ export type EventHandler = {
23
+ handler: (event: SQSEvent) => Promise<unknown>;
24
+ matcher: (subject: string) => boolean;
25
+ };
26
+ export {};
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.newEventsProxy = void 0;
40
+ var sqs_consumer_1 = require("sqs-consumer");
41
+ var mappers_1 = require("./mappers");
42
+ var logging_1 = require("@yopdev/logging");
43
+ var stoppable_1 = require("./stoppable");
44
+ var assert_1 = require("./assert");
45
+ var services_1 = require("./services");
46
+ var newEventsProxy = function (name, config, service) { return new services_1.Service(new EventsProxy(name, config.handlers), service); };
47
+ exports.newEventsProxy = newEventsProxy;
48
+ var EventsProxy = /** @class */ (function () {
49
+ function EventsProxy(name, handlers) {
50
+ var _this = this;
51
+ this.name = name;
52
+ this.handlers = handlers;
53
+ this.pollingFrequency = 1;
54
+ this.stopped = true;
55
+ this.start = function (config) { return __awaiter(_this, void 0, void 0, function () {
56
+ var _this = this;
57
+ return __generator(this, function (_a) {
58
+ return [2 /*return*/, this.queueConnectedToTopic(config.sns, config.topic.name, config.sqs, config.queue)
59
+ .then(function (url) { return _this.startEventsConsumer(config.sqs.client, url); })
60
+ .then(function (url) { return _this.LOGGER.debug('initialized: %s', url); })
61
+ .then(function () { return _this.stopped = false; })
62
+ .then(function () { return _this; })];
63
+ });
64
+ }); };
65
+ this.queueConnectedToTopic = function (sns, topic, sqs, queue) { return __awaiter(_this, void 0, void 0, function () {
66
+ return __generator(this, function (_a) {
67
+ return [2 /*return*/, Promise.all([
68
+ sns.createTopic(topic), sqs.createNamedQueue(queue)
69
+ ])
70
+ .then(function (values) { return sns
71
+ .createSubscription({ arn: values[0] }, { arn: values[1].arn })
72
+ .then(function () { return values[1].url; }); })];
73
+ });
74
+ }); };
75
+ this.startEventsConsumer = function (sqs, url) { return __awaiter(_this, void 0, void 0, function () {
76
+ var _this = this;
77
+ return __generator(this, function (_a) {
78
+ this.consumer = sqs_consumer_1.Consumer.create({
79
+ waitTimeSeconds: this.pollingFrequency,
80
+ queueUrl: url,
81
+ sqs: sqs,
82
+ handleMessage: function (message) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
83
+ return [2 /*return*/, this.onEachMessage(message)];
84
+ }); }); },
85
+ });
86
+ this.consumer.start();
87
+ return [2 /*return*/, url];
88
+ });
89
+ }); };
90
+ this.extractErrorMessage = function (e) { return typeof e === 'string' ? e : e.message !== undefined && typeof e.message === 'string' ? e.message : ''; };
91
+ this.onEachMessage = function (message) {
92
+ var body = (0, assert_1.assertNotUndefined)(message.Body, 'body is not present');
93
+ var subject = JSON.parse(body).Subject;
94
+ if (_this.stopped) {
95
+ _this.LOGGER.warn('stopped events proxy received message with subject %s', subject);
96
+ return;
97
+ }
98
+ var handlers = _this.handlers.filter(function (handler) { return handler.matcher(subject); });
99
+ if (handlers.length === 0) {
100
+ _this.LOGGER.warn('no handlers found for subject %s, message %o', subject, message);
101
+ }
102
+ handlers.forEach(function (handler) {
103
+ var record = (0, mappers_1.mapToLambdaSqsRecord)(message);
104
+ handler
105
+ .handler({ Records: [record] })
106
+ .then(function () {
107
+ var _a;
108
+ var json = JSON.parse(record.body);
109
+ var subject = json.Subject || ((_a = json.Message) === null || _a === void 0 ? void 0 : _a.eventname) || 'unknown';
110
+ _this.LOGGER.debug('subject accepted %s', subject);
111
+ })
112
+ .catch(function (e) {
113
+ var error = _this.extractErrorMessage(e);
114
+ _this.LOGGER.error(e, 'failed %s with %s', subject, error);
115
+ });
116
+ });
117
+ };
118
+ this.stop = function () { return __awaiter(_this, void 0, void 0, function () {
119
+ var _this = this;
120
+ return __generator(this, function (_a) {
121
+ return [2 /*return*/, Promise.resolve(this.consumer)
122
+ .then(function (consumer) { return consumer !== undefined ? (0, stoppable_1.stopConsumer)(consumer, _this.pollingFrequency).then(function () { return 'stopped'; }) : 'not started'; })
123
+ .then(function (status) { return _this.LOGGER.info(status); })];
124
+ });
125
+ }); };
126
+ this.LOGGER = logging_1.LoggerFactory.create("SNS->SQS[".concat(name, "]"));
127
+ }
128
+ return EventsProxy;
129
+ }());
@@ -0,0 +1,2 @@
1
+ import { Service } from "./services";
2
+ export declare const all: (services: Service<any>[]) => Service<any>;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ var _this = this;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.all = void 0;
5
+ var services_1 = require("./services");
6
+ var all = function (services) { return new services_1.Service({
7
+ name: "ALLOF[".concat(services.map(function (each) { return each.name; }).join(','), "]"),
8
+ start: function (config) { return Promise.all(services.map(function (each) { return each.start(config); })).then(function () { return _this; }); },
9
+ stop: function () { return Promise.all(services.map(function (each) { return each.stop(); })).then(); }
10
+ }, {}); };
11
+ exports.all = all;
@@ -0,0 +1,25 @@
1
+ /// <reference types="node" />
2
+ import { IncomingMessage, ServerResponse } from "http";
3
+ import { Lifecycle, Service, ServiceConfig } from "./services";
4
+ export declare const newHttpServer: (name: string, config: {
5
+ settings: HttpSettings;
6
+ handler: (request: IncomingMessage, requestBody: string, response: ServerResponse) => void;
7
+ }, service: ServiceConfig<string>) => Service<string>;
8
+ export declare class HttpServer implements Lifecycle<string> {
9
+ readonly name: string;
10
+ readonly settings: HttpSettings;
11
+ readonly handler: (request: IncomingMessage, requestBody: string, response: ServerResponse) => void;
12
+ private LOGGER;
13
+ private readonly protocol;
14
+ private address;
15
+ private readonly server;
16
+ constructor(name: string, settings: HttpSettings, handler: (request: IncomingMessage, requestBody: string, response: ServerResponse) => void);
17
+ start: () => Promise<string>;
18
+ private endpointUrl;
19
+ stop: () => Promise<void>;
20
+ }
21
+ export type HttpSettings = {
22
+ protocol: string;
23
+ host: string;
24
+ port: number | undefined;
25
+ };
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpServer = exports.newHttpServer = void 0;
4
+ var http_1 = require("http");
5
+ var events_1 = require("events");
6
+ var logging_1 = require("@yopdev/logging");
7
+ var assert_1 = require("./assert");
8
+ var services_1 = require("./services");
9
+ var newHttpServer = function (name, config, service) { return new services_1.Service(new HttpServer(name, config.settings, config.handler), service); };
10
+ exports.newHttpServer = newHttpServer;
11
+ var HttpServer = /** @class */ (function () {
12
+ function HttpServer(name, settings, handler) {
13
+ var _this = this;
14
+ this.name = name;
15
+ this.settings = settings;
16
+ this.handler = handler;
17
+ this.start = function () { return _this.server
18
+ .then(function () { return _this.LOGGER.info('listening on %s', (0, assert_1.assertNotUndefined)(_this.address).port); })
19
+ .then(function () { return _this.endpointUrl(); }); };
20
+ this.endpointUrl = function () {
21
+ var address = (0, assert_1.assertNotUndefined)(_this.address, 'server not started');
22
+ return "".concat(_this.protocol, "//").concat(address.address, ":").concat(address.port, "/");
23
+ };
24
+ this.stop = function () { return _this.server.then(function (server) { return server.close(); })
25
+ .then(function () { return _this.LOGGER.info('stop %s', (0, assert_1.assertNotUndefined)(_this.address).port); }); };
26
+ var server = (0, http_1.createServer)(function (req, res) {
27
+ req.setEncoding('utf-8');
28
+ var body = '';
29
+ req.on('data', function (chunks) { return body = body.concat(chunks); });
30
+ req.on('end', function () { return handler(req, body, res); });
31
+ })
32
+ .listen(settings.port, settings.host, function () { return _this.address = server.address(); });
33
+ this.server = (0, events_1.once)(server, 'listening')
34
+ .then(function () { return server; });
35
+ this.protocol = settings.protocol;
36
+ this.LOGGER = logging_1.LoggerFactory.create("HTTPSERVER[".concat(name, "]"));
37
+ }
38
+ return HttpServer;
39
+ }());
40
+ exports.HttpServer = HttpServer;
@@ -0,0 +1,10 @@
1
+ export { DevServer } from './dev-server';
2
+ export { newHttpServer as httpServer } from './http-server';
3
+ export { newLambdaHttpProxy as lambdaHttpProxy } from './lambda-http-proxy';
4
+ export { newSnsHttpProxy as snsHttpProxy } from './sns-http-proxy';
5
+ export { newInternalQueue as internalQueue } from './internal-queue';
6
+ export { newEventsProxy as eventsProxy } from './event-proxy';
7
+ export { newScheduledTasks as scheduledTasks } from './scheduled-tasks';
8
+ export { newPreTrafficHooks as preTrafficHooks } from './pre-traffic-hooks';
9
+ export { newDynamoDbTable as dynamoDbTable } from './dynamodb';
10
+ export { all as allOf } from './factories';
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.allOf = exports.dynamoDbTable = exports.preTrafficHooks = exports.scheduledTasks = exports.eventsProxy = exports.internalQueue = exports.snsHttpProxy = exports.lambdaHttpProxy = exports.httpServer = exports.DevServer = void 0;
4
+ var dev_server_1 = require("./dev-server");
5
+ Object.defineProperty(exports, "DevServer", { enumerable: true, get: function () { return dev_server_1.DevServer; } });
6
+ var http_server_1 = require("./http-server");
7
+ Object.defineProperty(exports, "httpServer", { enumerable: true, get: function () { return http_server_1.newHttpServer; } });
8
+ var lambda_http_proxy_1 = require("./lambda-http-proxy");
9
+ Object.defineProperty(exports, "lambdaHttpProxy", { enumerable: true, get: function () { return lambda_http_proxy_1.newLambdaHttpProxy; } });
10
+ var sns_http_proxy_1 = require("./sns-http-proxy");
11
+ Object.defineProperty(exports, "snsHttpProxy", { enumerable: true, get: function () { return sns_http_proxy_1.newSnsHttpProxy; } });
12
+ var internal_queue_1 = require("./internal-queue");
13
+ Object.defineProperty(exports, "internalQueue", { enumerable: true, get: function () { return internal_queue_1.newInternalQueue; } });
14
+ var event_proxy_1 = require("./event-proxy");
15
+ Object.defineProperty(exports, "eventsProxy", { enumerable: true, get: function () { return event_proxy_1.newEventsProxy; } });
16
+ var scheduled_tasks_1 = require("./scheduled-tasks");
17
+ Object.defineProperty(exports, "scheduledTasks", { enumerable: true, get: function () { return scheduled_tasks_1.newScheduledTasks; } });
18
+ var pre_traffic_hooks_1 = require("./pre-traffic-hooks");
19
+ Object.defineProperty(exports, "preTrafficHooks", { enumerable: true, get: function () { return pre_traffic_hooks_1.newPreTrafficHooks; } });
20
+ var dynamodb_1 = require("./dynamodb");
21
+ Object.defineProperty(exports, "dynamoDbTable", { enumerable: true, get: function () { return dynamodb_1.newDynamoDbTable; } });
22
+ var factories_1 = require("./factories");
23
+ Object.defineProperty(exports, "allOf", { enumerable: true, get: function () { return factories_1.all; } });
@@ -0,0 +1,7 @@
1
+ import { SQSEvent } from "aws-lambda";
2
+ import { Service, ServiceConfig } from "./services";
3
+ export declare const newInternalQueue: (name: string, config: {
4
+ index: number;
5
+ visibility: number;
6
+ handler: (e: SQSEvent) => Promise<void>;
7
+ }, service: ServiceConfig<string>) => Service<string>;
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.newInternalQueue = void 0;
40
+ var logging_1 = require("@yopdev/logging");
41
+ var sqs_consumer_1 = require("sqs-consumer");
42
+ var stoppable_1 = require("./stoppable");
43
+ var mappers_1 = require("./mappers");
44
+ var services_1 = require("./services");
45
+ var newInternalQueue = function (name, config, service) { return new services_1.Service(new InternalQueue(name, config.visibility, config.handler, config.index), service); };
46
+ exports.newInternalQueue = newInternalQueue;
47
+ var InternalQueue = /** @class */ (function () {
48
+ function InternalQueue(name, visibility, handler, index) {
49
+ var _this = this;
50
+ this.name = name;
51
+ this.visibility = visibility;
52
+ this.handler = handler;
53
+ this.start = function (config) { return _this.create(config.sqs); };
54
+ this.create = function (sqs) { return __awaiter(_this, void 0, void 0, function () {
55
+ var _this = this;
56
+ return __generator(this, function (_a) {
57
+ return [2 /*return*/, this.createQueue(sqs, this.queueName)
58
+ .then(function (queue) { return _this
59
+ .createConsumer(sqs.client, _this.queueName, queue.url, _this.handler, _this.visibility)
60
+ .then(function () { return queue.url; }); })];
61
+ });
62
+ }); };
63
+ this.createConsumer = function (sqs, name, url, handler, visibility) { return __awaiter(_this, void 0, void 0, function () {
64
+ var _this = this;
65
+ return __generator(this, function (_a) {
66
+ return [2 /*return*/, Promise.resolve(sqs_consumer_1.Consumer.create({
67
+ queueUrl: url,
68
+ waitTimeSeconds: visibility,
69
+ sqs: sqs,
70
+ handleMessage: function (message) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
71
+ return [2 /*return*/, handler({ Records: [(0, mappers_1.mapToLambdaSqsRecord)(message)] })];
72
+ }); }); },
73
+ }))
74
+ .then(function (consumer) {
75
+ consumer.on('error', function (err) {
76
+ _this.LOGGER.error(err, 'failed to handle message');
77
+ });
78
+ consumer.on('processing_error', function (err) {
79
+ _this.LOGGER.error(err, 'failed to process message');
80
+ });
81
+ consumer.start();
82
+ _this.LOGGER.info('consumer for %s initialized', name);
83
+ _this.state = {
84
+ consumer: consumer,
85
+ visibility: visibility,
86
+ };
87
+ })
88
+ .then(function () { return _this.LOGGER.info('started'); })
89
+ .then(function () { return _this; })];
90
+ });
91
+ }); };
92
+ this.stop = function () { return Promise.resolve(_this.state)
93
+ .then(function (state) { return state !== undefined ? (0, stoppable_1.stopConsumer)(state.consumer, state.visibility).then(function () { return 'stopped'; }) : 'not started'; })
94
+ .then(function (status) { return _this.LOGGER.info(status); }); };
95
+ this.queueName = (index + 1000).toString().padStart(10, '0');
96
+ this.LOGGER = logging_1.LoggerFactory.create("INTERNALQUEUE[".concat(name, "]"));
97
+ }
98
+ InternalQueue.prototype.createQueue = function (sqs, name) {
99
+ return __awaiter(this, void 0, void 0, function () {
100
+ var _this = this;
101
+ return __generator(this, function (_a) {
102
+ return [2 /*return*/, sqs
103
+ .createNamedQueue(name) //
104
+ .then(function (queue) {
105
+ _this.LOGGER.info('created: %s', queue.url);
106
+ return queue;
107
+ })];
108
+ });
109
+ });
110
+ };
111
+ return InternalQueue;
112
+ }());
@@ -0,0 +1,7 @@
1
+ import { HttpSettings } from "./http-server";
2
+ import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
3
+ import { Service, ServiceConfig } from "./services";
4
+ export declare const newLambdaHttpProxy: (name: string, config: {
5
+ settings: HttpSettings;
6
+ handler: (event: APIGatewayProxyEvent) => Promise<APIGatewayProxyResult>;
7
+ }, service: ServiceConfig<string>) => Service<string>;