@sn1006/common 1.0.24 → 1.0.27

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.
Files changed (35) hide show
  1. package/build/errors/bad-request-error.d.ts +3 -3
  2. package/build/errors/bad-request-error.js +6 -3
  3. package/build/errors/custom-error.d.ts +9 -0
  4. package/build/errors/custom-error.js +9 -0
  5. package/build/errors/db-error.d.ts +3 -3
  6. package/build/errors/db-error.js +6 -3
  7. package/build/errors/not-authorized-error.d.ts +3 -3
  8. package/build/errors/not-authorized-error.js +6 -3
  9. package/build/errors/not-found-error.d.ts +3 -3
  10. package/build/errors/not-found-error.js +6 -3
  11. package/build/errors/validation-error.d.ts +8 -11
  12. package/build/errors/validation-error.js +9 -5
  13. package/build/events/base-listener.d.ts +18 -0
  14. package/build/events/base-listener.js +31 -0
  15. package/build/events/base-publisher.d.ts +13 -0
  16. package/build/events/base-publisher.js +20 -0
  17. package/build/events/subjects.d.ts +4 -0
  18. package/build/events/subjects.js +8 -0
  19. package/build/events/ticket-created-event.d.ts +10 -0
  20. package/build/events/ticket-created-event.js +2 -0
  21. package/build/events/ticket-updated-event.d.ts +10 -0
  22. package/build/events/ticket-updated-event.js +2 -0
  23. package/build/index.d.ts +6 -4
  24. package/build/index.js +6 -4
  25. package/build/middlewares/error-handler.js +7 -4
  26. package/build/middlewares/validate-request.js +3 -8
  27. package/package.json +2 -3
  28. package/build/errors/normalized-error.d.ts +0 -9
  29. package/build/errors/normalized-error.js +0 -11
  30. package/build/middlewares/async-wrapper.d.ts +0 -3
  31. package/build/middlewares/async-wrapper.js +0 -7
  32. package/build/middlewares/joi-validate-request.d.ts +0 -4
  33. package/build/middlewares/joi-validate-request.js +0 -24
  34. package/build/middlewares/zod-validate-request.d.ts +0 -4
  35. package/build/middlewares/zod-validate-request.js +0 -27
@@ -1,9 +1,9 @@
1
- import { NormalizedError } from './normalized-error';
2
- export declare class BadRequestError extends NormalizedError {
1
+ import CustomError from './custom-error';
2
+ export declare class BadRequestError extends CustomError {
3
3
  message: string;
4
4
  status: number;
5
5
  constructor(message: string);
6
- serializeErrors(): {
6
+ serializeError(): {
7
7
  message: string;
8
8
  }[];
9
9
  }
@@ -1,15 +1,18 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.BadRequestError = void 0;
4
- const normalized_error_1 = require("./normalized-error");
5
- class BadRequestError extends normalized_error_1.NormalizedError {
7
+ const custom_error_1 = __importDefault(require("./custom-error"));
8
+ class BadRequestError extends custom_error_1.default {
6
9
  constructor(message) {
7
10
  super(message);
8
11
  this.message = message;
9
12
  this.status = 400;
10
13
  Object.setPrototypeOf(this, BadRequestError.prototype);
11
14
  }
12
- serializeErrors() {
15
+ serializeError() {
13
16
  return [{ message: this.message }];
14
17
  }
15
18
  }
@@ -0,0 +1,9 @@
1
+ declare abstract class CustomError extends Error {
2
+ abstract status: number;
3
+ constructor(message: string);
4
+ abstract serializeError(): {
5
+ message: string;
6
+ field?: string;
7
+ }[];
8
+ }
9
+ export default CustomError;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class CustomError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ Object.setPrototypeOf(this, CustomError.prototype);
7
+ }
8
+ }
9
+ exports.default = CustomError;
@@ -1,8 +1,8 @@
1
- import { NormalizedError } from './normalized-error';
2
- export default class DBError extends NormalizedError {
1
+ import CustomError from './custom-error';
2
+ export default class DBError extends CustomError {
3
3
  status: number;
4
4
  constructor();
5
- serializeErrors(): {
5
+ serializeError(): {
6
6
  message: string;
7
7
  field?: string | undefined;
8
8
  }[];
@@ -1,13 +1,16 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const normalized_error_1 = require("./normalized-error");
4
- class DBError extends normalized_error_1.NormalizedError {
6
+ const custom_error_1 = __importDefault(require("./custom-error"));
7
+ class DBError extends custom_error_1.default {
5
8
  constructor() {
6
9
  super('Error connecting to DB');
7
10
  this.status = 500;
8
11
  Object.setPrototypeOf(this, DBError.prototype);
9
12
  }
10
- serializeErrors() {
13
+ serializeError() {
11
14
  return [{ message: this.message }];
12
15
  }
13
16
  }
@@ -1,8 +1,8 @@
1
- import { NormalizedError } from './normalized-error';
2
- export declare class NotAuthorizedError extends NormalizedError {
1
+ import CustomError from './custom-error';
2
+ export declare class NotAuthorizedError extends CustomError {
3
3
  status: number;
4
4
  constructor();
5
- serializeErrors(): {
5
+ serializeError(): {
6
6
  message: string;
7
7
  }[];
8
8
  }
@@ -1,14 +1,17 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.NotAuthorizedError = void 0;
4
- const normalized_error_1 = require("./normalized-error");
5
- class NotAuthorizedError extends normalized_error_1.NormalizedError {
7
+ const custom_error_1 = __importDefault(require("./custom-error"));
8
+ class NotAuthorizedError extends custom_error_1.default {
6
9
  constructor() {
7
10
  super('Not authorized');
8
11
  this.status = 401;
9
12
  Object.setPrototypeOf(this, NotAuthorizedError.prototype);
10
13
  }
11
- serializeErrors() {
14
+ serializeError() {
12
15
  return [{ message: this.message }];
13
16
  }
14
17
  }
@@ -1,8 +1,8 @@
1
- import { NormalizedError } from './normalized-error';
2
- export declare class NotFoundError extends NormalizedError {
1
+ import CustomError from './custom-error';
2
+ export declare class NotFoundError extends CustomError {
3
3
  status: number;
4
4
  constructor();
5
- serializeErrors(): {
5
+ serializeError(): {
6
6
  message: string;
7
7
  }[];
8
8
  }
@@ -1,14 +1,17 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.NotFoundError = void 0;
4
- const normalized_error_1 = require("./normalized-error");
5
- class NotFoundError extends normalized_error_1.NormalizedError {
7
+ const custom_error_1 = __importDefault(require("./custom-error"));
8
+ class NotFoundError extends custom_error_1.default {
6
9
  constructor() {
7
10
  super("Resource not found");
8
11
  this.status = 404;
9
12
  Object.setPrototypeOf(this, NotFoundError.prototype);
10
13
  }
11
- serializeErrors() {
14
+ serializeError() {
12
15
  return [{ message: this.message }];
13
16
  }
14
17
  }
@@ -1,15 +1,12 @@
1
- import { NormalizedError } from './normalized-error';
2
- interface NonSerializedValidationError {
3
- message: string;
4
- path: (string | number)[];
5
- }
6
- declare class CustomValidationError extends NormalizedError {
7
- errors: NonSerializedValidationError[];
1
+ import CustomError from './custom-error';
2
+ import { ValidationError } from 'express-validator';
3
+ declare class CustomValidationError extends CustomError {
4
+ errors: ValidationError[];
8
5
  status: number;
9
- constructor(errors: NonSerializedValidationError[]);
10
- serializeErrors(): {
11
- message: string;
12
- path: (string | number)[];
6
+ constructor(errors: ValidationError[]);
7
+ serializeError(): {
8
+ message: any;
9
+ field: string;
13
10
  }[];
14
11
  }
15
12
  export default CustomValidationError;
@@ -1,16 +1,20 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const normalized_error_1 = require("./normalized-error");
4
- class CustomValidationError extends normalized_error_1.NormalizedError {
6
+ const custom_error_1 = __importDefault(require("./custom-error"));
7
+ class CustomValidationError extends custom_error_1.default {
5
8
  constructor(errors) {
6
- super("Validaton error");
9
+ super("Invalid username or password");
7
10
  this.errors = errors;
8
11
  this.status = 400;
9
12
  Object.setPrototypeOf(this, CustomValidationError.prototype);
10
13
  }
11
- serializeErrors() {
14
+ serializeError() {
12
15
  return this.errors.map(err => {
13
- return { message: err.message, path: err.path };
16
+ const ferr = err;
17
+ return { message: ferr.msg, field: ferr.path };
14
18
  });
15
19
  }
16
20
  }
@@ -0,0 +1,18 @@
1
+ import { Message, Stan } from "node-nats-streaming";
2
+ import { Subjects } from "./subjects";
3
+ interface Event {
4
+ subject: Subjects;
5
+ data: any;
6
+ }
7
+ export declare abstract class Listener<T extends Event> {
8
+ abstract subject: T['subject'];
9
+ abstract queueGroupName: string;
10
+ abstract onMessage(data: T['data'], msg: Message): void;
11
+ private client;
12
+ protected ackWait: number;
13
+ constructor(client: Stan);
14
+ subscriptionOptions(): import("node-nats-streaming").SubscriptionOptions;
15
+ listen(): void;
16
+ parseMessage(msg: Message): any;
17
+ }
18
+ export {};
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Listener = void 0;
4
+ class Listener {
5
+ constructor(client) {
6
+ this.ackWait = 5 * 1000;
7
+ this.client = client;
8
+ }
9
+ subscriptionOptions() {
10
+ return this.client.subscriptionOptions()
11
+ .setDeliverAllAvailable()
12
+ .setManualAckMode(true)
13
+ .setAckWait(this.ackWait)
14
+ .setDurableName(this.queueGroupName);
15
+ }
16
+ listen() {
17
+ const subscription = this.client.subscribe(this.subject, this.queueGroupName, this.subscriptionOptions());
18
+ subscription.on('message', (msg) => {
19
+ console.log(`Message received ${this.subject} / ${this.queueGroupName}`);
20
+ const parsedData = this.parseMessage(msg);
21
+ this.onMessage(parsedData, msg);
22
+ });
23
+ }
24
+ parseMessage(msg) {
25
+ const data = msg.getData();
26
+ return typeof data === 'string'
27
+ ? JSON.parse(data)
28
+ : JSON.parse(data.toString('utf8'));
29
+ }
30
+ }
31
+ exports.Listener = Listener;
@@ -0,0 +1,13 @@
1
+ import { Stan } from "node-nats-streaming";
2
+ import { Subjects } from "./subjects";
3
+ interface Event {
4
+ subject: Subjects;
5
+ data: any;
6
+ }
7
+ export declare abstract class Publisher<T extends Event> {
8
+ abstract subject: T['subject'];
9
+ private client;
10
+ constructor(client: Stan);
11
+ publish(data: T['data']): Promise<void>;
12
+ }
13
+ export {};
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Publisher = void 0;
4
+ class Publisher {
5
+ constructor(client) {
6
+ this.client = client;
7
+ }
8
+ publish(data) {
9
+ return new Promise((resolve, reject) => {
10
+ this.client.publish(this.subject, JSON.stringify(data), (err) => {
11
+ if (err) {
12
+ return reject(err);
13
+ }
14
+ console.log('Event publishe to subject', this.subject);
15
+ resolve();
16
+ });
17
+ });
18
+ }
19
+ }
20
+ exports.Publisher = Publisher;
@@ -0,0 +1,4 @@
1
+ export declare enum Subjects {
2
+ TicketCreated = "ticket:created",
3
+ TicketUpdated = "ticket:updated"
4
+ }
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Subjects = void 0;
4
+ var Subjects;
5
+ (function (Subjects) {
6
+ Subjects["TicketCreated"] = "ticket:created";
7
+ Subjects["TicketUpdated"] = "ticket:updated";
8
+ })(Subjects || (exports.Subjects = Subjects = {}));
@@ -0,0 +1,10 @@
1
+ import { Subjects } from "./subjects";
2
+ export interface TicketCreatedEvent {
3
+ subject: Subjects.TicketCreated;
4
+ data: {
5
+ id: string;
6
+ title: string;
7
+ price: number;
8
+ userId: string;
9
+ };
10
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,10 @@
1
+ import { Subjects } from "./subjects";
2
+ export interface TicketUpdatedEvent {
3
+ subject: Subjects.TicketUpdated;
4
+ data: {
5
+ id: string;
6
+ title: string;
7
+ price: number;
8
+ userId: string;
9
+ };
10
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/build/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export * from './errors/bad-request-error';
2
- export * from './errors/normalized-error';
2
+ export * from './errors/custom-error';
3
3
  export * from './errors/db-error';
4
4
  export * from './errors/validation-error';
5
5
  export * from './errors/not-authorized-error';
@@ -8,6 +8,8 @@ export * from './middlewares/current-user';
8
8
  export * from './middlewares/error-handler';
9
9
  export * from './middlewares/require-auth';
10
10
  export * from './middlewares/validate-request';
11
- export * from './middlewares/joi-validate-request';
12
- export * from './middlewares/zod-validate-request';
13
- export * from './middlewares/async-wrapper';
11
+ export * from './events/base-listener';
12
+ export * from './events/base-publisher';
13
+ export * from './events/subjects';
14
+ export * from './events/ticket-created-event';
15
+ export * from './events/ticket-updated-event';
package/build/index.js CHANGED
@@ -15,7 +15,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./errors/bad-request-error"), exports);
18
- __exportStar(require("./errors/normalized-error"), exports);
18
+ __exportStar(require("./errors/custom-error"), exports);
19
19
  __exportStar(require("./errors/db-error"), exports);
20
20
  __exportStar(require("./errors/validation-error"), exports);
21
21
  __exportStar(require("./errors/not-authorized-error"), exports);
@@ -24,6 +24,8 @@ __exportStar(require("./middlewares/current-user"), exports);
24
24
  __exportStar(require("./middlewares/error-handler"), exports);
25
25
  __exportStar(require("./middlewares/require-auth"), exports);
26
26
  __exportStar(require("./middlewares/validate-request"), exports);
27
- __exportStar(require("./middlewares/joi-validate-request"), exports);
28
- __exportStar(require("./middlewares/zod-validate-request"), exports);
29
- __exportStar(require("./middlewares/async-wrapper"), exports);
27
+ __exportStar(require("./events/base-listener"), exports);
28
+ __exportStar(require("./events/base-publisher"), exports);
29
+ __exportStar(require("./events/subjects"), exports);
30
+ __exportStar(require("./events/ticket-created-event"), exports);
31
+ __exportStar(require("./events/ticket-updated-event"), exports);
@@ -1,12 +1,15 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.errorHandler = void 0;
4
- const normalized_error_1 = require("../errors/normalized-error");
7
+ const custom_error_1 = __importDefault(require("../errors/custom-error"));
5
8
  const errorHandler = (err, req, res, next) => {
6
- console.log(err);
7
- if (err instanceof normalized_error_1.NormalizedError) {
8
- return res.status(err.status).send(err.serializeErrors());
9
+ if (err instanceof custom_error_1.default) {
10
+ return res.status(err.status).send(err.serializeError());
9
11
  }
12
+ console.error(err);
10
13
  return res.status(400).send('Something went wrong');
11
14
  };
12
15
  exports.errorHandler = errorHandler;
@@ -7,14 +7,9 @@ exports.validateRequest = void 0;
7
7
  const express_validator_1 = require("express-validator");
8
8
  const validation_error_1 = __importDefault(require("../errors/validation-error"));
9
9
  const validateRequest = (req, res, next) => {
10
- const error = (0, express_validator_1.validationResult)(req);
11
- if (!error.isEmpty()) {
12
- const errors = error.array();
13
- const cleanedErrors = errors.map((err) => ({
14
- path: err.path.split("."),
15
- message: err.msg
16
- }));
17
- return next(new validation_error_1.default(cleanedErrors));
10
+ const errors = (0, express_validator_1.validationResult)(req);
11
+ if (!errors.isEmpty()) {
12
+ return next(new validation_error_1.default(errors.array()));
18
13
  }
19
14
  next();
20
15
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sn1006/common",
3
- "version": "1.0.24",
3
+ "version": "1.0.27",
4
4
  "description": "",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -26,8 +26,7 @@
26
26
  "cookie-session": "^2.0.0",
27
27
  "express": "^4.18.2",
28
28
  "express-validator": "^7.0.1",
29
- "joi": "^17.12.1",
30
29
  "jsonwebtoken": "^9.0.1",
31
- "zod": "^3.22.4"
30
+ "node-nats-streaming": "^0.3.2"
32
31
  }
33
32
  }
@@ -1,9 +0,0 @@
1
- export declare abstract class NormalizedError extends Error {
2
- abstract status: number;
3
- constructor(message: string);
4
- abstract serializeErrors(): SerializedError[];
5
- }
6
- export interface SerializedError {
7
- message: string;
8
- path?: (string | number)[];
9
- }
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NormalizedError = void 0;
4
- // the purpose of this class is to "normalize" errors between services
5
- class NormalizedError extends Error {
6
- constructor(message) {
7
- super(message);
8
- Object.setPrototypeOf(this, NormalizedError.prototype);
9
- }
10
- }
11
- exports.NormalizedError = NormalizedError;
@@ -1,3 +0,0 @@
1
- import { NextFunction, Request, Response } from "express";
2
- declare const asyncWrapper: (asyncMiddleware: (req: Request, res: Response, next: NextFunction) => Promise<any>) => (req: Request, res: Response, next: NextFunction) => Promise<any>;
3
- export { asyncWrapper };
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.asyncWrapper = void 0;
4
- const asyncWrapper = (asyncMiddleware) => {
5
- return (req, res, next) => asyncMiddleware(req, res, next).catch(err => next(err));
6
- };
7
- exports.asyncWrapper = asyncWrapper;
@@ -1,4 +0,0 @@
1
- import { NextFunction, Request, Response } from "express";
2
- import Joi from "joi";
3
- declare function joiValidateRequest(schema: Joi.AnySchema, options?: Joi.ValidationOptions): (req: Request, res: Response, next: NextFunction) => any;
4
- export { joiValidateRequest };
@@ -1,24 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.joiValidateRequest = void 0;
7
- const validation_error_1 = __importDefault(require("../errors/validation-error"));
8
- function joiValidateRequest(schema, options) {
9
- return (req, res, next) => {
10
- const { error } = schema.validate(req, options);
11
- if (error) {
12
- // normalized the error to be similar to express-validator error
13
- // const errors = error.details.map((err) => ({
14
- // ...err,
15
- // msg: err.message,
16
- // path: err.path.join("."),
17
- // }));
18
- const errors = error.details;
19
- return next(new validation_error_1.default(errors));
20
- }
21
- return next();
22
- };
23
- }
24
- exports.joiValidateRequest = joiValidateRequest;
@@ -1,4 +0,0 @@
1
- import { NextFunction, Request, Response } from "express";
2
- import { ZodSchema } from "zod";
3
- declare function zodValidateRequest(schema: ZodSchema): (req: Request, res: Response, next: NextFunction) => Promise<void>;
4
- export { zodValidateRequest };
@@ -1,27 +0,0 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.zodValidateRequest = void 0;
16
- const validation_error_1 = __importDefault(require("../errors/validation-error"));
17
- function zodValidateRequest(schema) {
18
- return (req, res, next) => __awaiter(this, void 0, void 0, function* () {
19
- const result = schema.safeParse(req.body);
20
- if (!result.success) {
21
- const errors = result.error.issues;
22
- return next(new validation_error_1.default(errors));
23
- }
24
- return next();
25
- });
26
- }
27
- exports.zodValidateRequest = zodValidateRequest;