@eratu/common 1.0.0 → 1.0.2

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,9 @@
1
+ import { CustomError } from './custom-error';
2
+ export declare class BadRequestError extends CustomError {
3
+ message: string;
4
+ statusCode: number;
5
+ constructor(message: string);
6
+ serializeErrors(): {
7
+ message: string;
8
+ }[];
9
+ }
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BadRequestError = void 0;
4
+ const custom_error_1 = require("./custom-error");
5
+ class BadRequestError extends custom_error_1.CustomError {
6
+ constructor(message) {
7
+ super(message);
8
+ this.message = message;
9
+ this.statusCode = 400;
10
+ Object.setPrototypeOf(this, BadRequestError.prototype);
11
+ }
12
+ serializeErrors() {
13
+ return [{ message: this.message }];
14
+ }
15
+ }
16
+ exports.BadRequestError = BadRequestError;
@@ -0,0 +1,8 @@
1
+ export declare abstract class CustomError extends Error {
2
+ abstract statusCode: number;
3
+ constructor(message: string);
4
+ abstract serializeErrors(): {
5
+ message: string;
6
+ field?: string;
7
+ }[];
8
+ }
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CustomError = void 0;
4
+ class CustomError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ Object.setPrototypeOf(this, CustomError.prototype);
8
+ }
9
+ }
10
+ exports.CustomError = CustomError;
@@ -0,0 +1,9 @@
1
+ import { CustomError } from './custom-error';
2
+ export declare class DatabaseConnectionError extends CustomError {
3
+ statusCode: number;
4
+ reason: string;
5
+ constructor();
6
+ serializeErrors(): {
7
+ message: string;
8
+ }[];
9
+ }
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DatabaseConnectionError = void 0;
4
+ const custom_error_1 = require("./custom-error");
5
+ class DatabaseConnectionError extends custom_error_1.CustomError {
6
+ constructor() {
7
+ super('Error connecting to db');
8
+ this.statusCode = 500;
9
+ this.reason = 'Error connecting to database';
10
+ Object.setPrototypeOf(this, DatabaseConnectionError.prototype);
11
+ }
12
+ serializeErrors() {
13
+ return [{ message: this.reason }];
14
+ }
15
+ }
16
+ exports.DatabaseConnectionError = DatabaseConnectionError;
@@ -0,0 +1,8 @@
1
+ import { CustomError } from './custom-error';
2
+ export declare class NotAuthorizedError extends CustomError {
3
+ statusCode: number;
4
+ constructor();
5
+ serializeErrors(): {
6
+ message: string;
7
+ }[];
8
+ }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NotAuthorizedError = void 0;
4
+ const custom_error_1 = require("./custom-error");
5
+ class NotAuthorizedError extends custom_error_1.CustomError {
6
+ constructor() {
7
+ super('Not Authorized');
8
+ this.statusCode = 401;
9
+ Object.setPrototypeOf(this, NotAuthorizedError.prototype);
10
+ }
11
+ serializeErrors() {
12
+ return [{ message: 'Not authorized' }];
13
+ }
14
+ }
15
+ exports.NotAuthorizedError = NotAuthorizedError;
@@ -0,0 +1,8 @@
1
+ import { CustomError } from './custom-error';
2
+ export declare class NotFoundError extends CustomError {
3
+ statusCode: number;
4
+ constructor();
5
+ serializeErrors(): {
6
+ message: string;
7
+ }[];
8
+ }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NotFoundError = void 0;
4
+ const custom_error_1 = require("./custom-error");
5
+ class NotFoundError extends custom_error_1.CustomError {
6
+ constructor() {
7
+ super('Route not found');
8
+ this.statusCode = 404;
9
+ Object.setPrototypeOf(this, NotFoundError.prototype);
10
+ }
11
+ serializeErrors() {
12
+ return [{ message: 'Not Found' }];
13
+ }
14
+ }
15
+ exports.NotFoundError = NotFoundError;
@@ -0,0 +1,14 @@
1
+ import { ValidationError } from 'express-validator';
2
+ import { CustomError } from './custom-error';
3
+ export declare class RequestValidationError extends CustomError {
4
+ errors: ValidationError[];
5
+ statusCode: number;
6
+ constructor(errors: ValidationError[]);
7
+ serializeErrors(): ({
8
+ message: any;
9
+ field: string;
10
+ } | {
11
+ message: any;
12
+ field?: undefined;
13
+ })[];
14
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RequestValidationError = void 0;
4
+ const custom_error_1 = require("./custom-error");
5
+ class RequestValidationError extends custom_error_1.CustomError {
6
+ constructor(errors) {
7
+ super('Invalid request parameters');
8
+ this.errors = errors;
9
+ this.statusCode = 400;
10
+ // Only because we are extending a built in class
11
+ Object.setPrototypeOf(this, RequestValidationError.prototype);
12
+ }
13
+ serializeErrors() {
14
+ return this.errors.map((err) => {
15
+ if (err.type === 'field') {
16
+ return { message: err.msg, field: err.path };
17
+ }
18
+ return { message: err.msg };
19
+ });
20
+ }
21
+ }
22
+ exports.RequestValidationError = RequestValidationError;
@@ -0,0 +1,22 @@
1
+ import { JetStreamManager, JsMsg, Consumer, JetStreamClient } from "nats";
2
+ interface Event {
3
+ subject: string;
4
+ stream: string;
5
+ data: any;
6
+ }
7
+ export declare abstract class Listener<T extends Event> {
8
+ abstract subject: T["subject"];
9
+ abstract stream: T["stream"];
10
+ abstract durableName: string;
11
+ abstract onMessage(data: T["data"], msg: JsMsg): void;
12
+ protected jsm: JetStreamManager;
13
+ protected js: JetStreamClient;
14
+ protected consumer: Consumer;
15
+ protected ackWait: number;
16
+ protected codec: import("nats").Codec<unknown>;
17
+ constructor(js: JetStreamClient, jsm: JetStreamManager);
18
+ private ensureStreamAndConsumer;
19
+ listen(): Promise<void>;
20
+ private parseMessage;
21
+ }
22
+ export {};
@@ -0,0 +1,74 @@
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 __asyncValues = (this && this.__asyncValues) || function (o) {
12
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
+ var m = o[Symbol.asyncIterator], i;
14
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.Listener = void 0;
20
+ const nats_1 = require("nats");
21
+ class Listener {
22
+ constructor(js, jsm) {
23
+ this.ackWait = 5 * 1000;
24
+ this.codec = (0, nats_1.JSONCodec)();
25
+ this.jsm = jsm;
26
+ this.js = js;
27
+ }
28
+ ensureStreamAndConsumer() {
29
+ return __awaiter(this, void 0, void 0, function* () {
30
+ // Ensure durable consumer exists
31
+ try {
32
+ yield this.jsm.consumers.info(this.stream, this.durableName);
33
+ }
34
+ catch (_a) {
35
+ yield this.jsm.consumers.add(this.stream, {
36
+ durable_name: this.durableName,
37
+ ack_policy: nats_1.AckPolicy.Explicit,
38
+ ack_wait: this.ackWait * 1000000, // nanoseconds
39
+ filter_subject: this.subject,
40
+ });
41
+ }
42
+ // Get the consumer object
43
+ this.consumer = yield this.js.consumers.get(this.stream, this.durableName);
44
+ });
45
+ }
46
+ listen() {
47
+ return __awaiter(this, void 0, void 0, function* () {
48
+ var _a, e_1, _b, _c;
49
+ yield this.ensureStreamAndConsumer();
50
+ const messages = yield this.consumer.consume();
51
+ try {
52
+ for (var _d = true, messages_1 = __asyncValues(messages), messages_1_1; messages_1_1 = yield messages_1.next(), _a = messages_1_1.done, !_a; _d = true) {
53
+ _c = messages_1_1.value;
54
+ _d = false;
55
+ const msg = _c;
56
+ const data = this.parseMessage(msg);
57
+ yield this.onMessage(data, msg);
58
+ }
59
+ }
60
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
61
+ finally {
62
+ try {
63
+ if (!_d && !_a && (_b = messages_1.return)) yield _b.call(messages_1);
64
+ }
65
+ finally { if (e_1) throw e_1.error; }
66
+ }
67
+ });
68
+ }
69
+ parseMessage(msg) {
70
+ const decoded = this.codec.decode(msg.data);
71
+ return decoded;
72
+ }
73
+ }
74
+ exports.Listener = Listener;
@@ -0,0 +1,11 @@
1
+ import { Streams } from "./streams";
2
+ import { Subjects } from "./subjects";
3
+ export interface BookCreatedEvent {
4
+ subject: Subjects.BookCreated;
5
+ stream: Streams.BookServiceStream;
6
+ data: {
7
+ id: string;
8
+ version: number;
9
+ title: string;
10
+ };
11
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,5 @@
1
+ export declare enum Streams {
2
+ OrderServiceStream = "orders",
3
+ BookServiceStream = "books",
4
+ UserServiceStream = "users"
5
+ }
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Streams = void 0;
4
+ var Streams;
5
+ (function (Streams) {
6
+ Streams["OrderServiceStream"] = "orders";
7
+ Streams["BookServiceStream"] = "books";
8
+ Streams["UserServiceStream"] = "users";
9
+ })(Streams || (exports.Streams = Streams = {}));
@@ -0,0 +1,6 @@
1
+ export declare enum Subjects {
2
+ UserRegistered = "user:registered",
3
+ BookCreated = "book:created",
4
+ OrderCreated = "order:created",
5
+ OrderCancelled = "order:cancelled"
6
+ }
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Subjects = void 0;
4
+ var Subjects;
5
+ (function (Subjects) {
6
+ Subjects["UserRegistered"] = "user:registered";
7
+ Subjects["BookCreated"] = "book:created";
8
+ Subjects["OrderCreated"] = "order:created";
9
+ Subjects["OrderCancelled"] = "order:cancelled";
10
+ })(Subjects || (exports.Subjects = Subjects = {}));
@@ -0,0 +1,10 @@
1
+ export * from "./errors/bad-request-error";
2
+ export * from "./errors/custom-error";
3
+ export * from "./errors/database-connection-error";
4
+ export * from "./errors/not-authorized-error";
5
+ export * from "./errors/not-found-error";
6
+ export * from "./errors/request-validation-error";
7
+ export * from "./events/base-listener";
8
+ export * from "./events/book-created-event";
9
+ export * from "./events/subjects";
10
+ export * from "./events/streams";
package/build/index.js ADDED
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./errors/bad-request-error"), exports);
18
+ __exportStar(require("./errors/custom-error"), exports);
19
+ __exportStar(require("./errors/database-connection-error"), exports);
20
+ __exportStar(require("./errors/not-authorized-error"), exports);
21
+ __exportStar(require("./errors/not-found-error"), exports);
22
+ __exportStar(require("./errors/request-validation-error"), exports);
23
+ __exportStar(require("./events/base-listener"), exports);
24
+ __exportStar(require("./events/book-created-event"), exports);
25
+ __exportStar(require("./events/subjects"), exports);
26
+ __exportStar(require("./events/streams"), exports);
package/package.json CHANGED
@@ -1,13 +1,30 @@
1
1
  {
2
2
  "name": "@eratu/common",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "A package for shared code across microservices",
5
- "main": "index.js",
5
+ "main": "./build/index.js",
6
+ "types": "./build/index.d.ts",
7
+ "files": [
8
+ "build/**/*"
9
+ ],
6
10
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
11
+ "clean": "del ./build/*",
12
+ "build": "tsc",
13
+ "pub": "git add . && git commit -m \"Updates\" && npm version patch && npm publish"
8
14
  },
9
15
  "keywords": [],
10
16
  "author": "",
11
17
  "license": "ISC",
12
- "type": "commonjs"
18
+ "type": "commonjs",
19
+ "devDependencies": {
20
+ "del-cli": "^6.0.0",
21
+ "typescript": "^5.7.3"
22
+ },
23
+ "dependencies": {
24
+ "@types/express": "^5.0.0",
25
+ "cookie-session": "^2.1.0",
26
+ "express": "^4.21.2",
27
+ "express-validator": "^7.2.1",
28
+ "nats": "^2.29.3"
29
+ }
13
30
  }