@common_ch/common 1.0.4 → 1.0.6

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 (39) hide show
  1. package/build/errors/bad-request-error.d.ts +11 -0
  2. package/build/errors/bad-request-error.js +17 -0
  3. package/build/errors/custom-error.d.ts +23 -0
  4. package/build/errors/custom-error.js +11 -0
  5. package/build/errors/not-authorized-error.d.ts +10 -0
  6. package/build/errors/not-authorized-error.js +16 -0
  7. package/build/errors/notfound.d.ts +10 -0
  8. package/build/errors/notfound.js +19 -0
  9. package/build/errors/request-validation-error.d.ts +22 -0
  10. package/build/errors/request-validation-error.js +29 -0
  11. package/build/errors/user-not-found-error.d.ts +14 -0
  12. package/build/errors/user-not-found-error.js +24 -0
  13. package/build/events/base-listener.d.ts +18 -0
  14. package/build/events/base-listener.js +32 -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 +3 -0
  18. package/build/events/subjects.js +7 -0
  19. package/build/events/user/user-created-event.d.ts +12 -0
  20. package/build/events/user/user-created-event.js +2 -0
  21. package/{src/index.ts → build/index.d.ts} +4 -2
  22. package/build/index.js +29 -0
  23. package/build/middlewares/current-user.d.ts +16 -0
  24. package/build/middlewares/current-user.js +20 -0
  25. package/build/middlewares/error-handler.d.ts +2 -0
  26. package/build/middlewares/error-handler.js +17 -0
  27. package/build/middlewares/require-auth.d.ts +2 -0
  28. package/build/middlewares/require-auth.js +11 -0
  29. package/package.json +8 -3
  30. package/src/errors/bad-request-error.ts +0 -14
  31. package/src/errors/custom-error.ts +0 -22
  32. package/src/errors/not-authorized-error.ts +0 -13
  33. package/src/errors/notfound.ts +0 -18
  34. package/src/errors/request-validation-error.ts +0 -28
  35. package/src/errors/user-not-found-error.ts +0 -20
  36. package/src/middlewares/current-user.ts +0 -30
  37. package/src/middlewares/error-handler.ts +0 -15
  38. package/src/middlewares/require-auth.ts +0 -11
  39. package/tsconfig.json +0 -101
@@ -0,0 +1,11 @@
1
+ import { CustomError } from './custom-error';
2
+ export declare class BadRequestError extends CustomError {
3
+ message: string;
4
+ statusCode: number;
5
+ name: string;
6
+ constructor(message: string);
7
+ serializeErrors(): {
8
+ message: string;
9
+ name: string;
10
+ };
11
+ }
@@ -0,0 +1,17 @@
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
+ this.name = 'bad_request_error';
11
+ Object.setPrototypeOf(this, BadRequestError.prototype);
12
+ }
13
+ serializeErrors() {
14
+ return { message: this.message, name: this.name };
15
+ }
16
+ }
17
+ exports.BadRequestError = BadRequestError;
@@ -0,0 +1,23 @@
1
+ export declare const optionsValidation: {
2
+ abortEarly: boolean;
3
+ allowUnknown: boolean;
4
+ stripUnknown: boolean;
5
+ };
6
+ export interface ValidationError {
7
+ message: string;
8
+ type: string;
9
+ }
10
+ export interface JoiError {
11
+ original: unknown;
12
+ details: ValidationError[];
13
+ }
14
+ export declare abstract class CustomError extends Error {
15
+ abstract statusCode: number;
16
+ abstract name: string;
17
+ constructor(message: string);
18
+ abstract serializeErrors(): {
19
+ message: string;
20
+ name: string;
21
+ errors?: JoiError;
22
+ };
23
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CustomError = exports.optionsValidation = void 0;
4
+ exports.optionsValidation = { abortEarly: false, allowUnknown: false, stripUnknown: false };
5
+ class CustomError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ Object.setPrototypeOf(this, CustomError.prototype);
9
+ }
10
+ }
11
+ exports.CustomError = CustomError;
@@ -0,0 +1,10 @@
1
+ import { CustomError } from './custom-error';
2
+ export declare class NotAuthorizedError extends CustomError {
3
+ statusCode: number;
4
+ name: string;
5
+ constructor();
6
+ serializeErrors(): {
7
+ message: string;
8
+ name: string;
9
+ };
10
+ }
@@ -0,0 +1,16 @@
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
+ this.name = 'not-authorized-error';
10
+ Object.setPrototypeOf(this, NotAuthorizedError.prototype);
11
+ }
12
+ serializeErrors() {
13
+ return { message: 'Not authorized', name: this.name };
14
+ }
15
+ }
16
+ exports.NotAuthorizedError = NotAuthorizedError;
@@ -0,0 +1,10 @@
1
+ import { CustomError } from './custom-error';
2
+ export declare class NotFoundError extends CustomError {
3
+ statusCode: number;
4
+ name: string;
5
+ constructor();
6
+ serializeErrors(): {
7
+ message: string;
8
+ name: string;
9
+ };
10
+ }
@@ -0,0 +1,19 @@
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('Rout Not Found');
8
+ this.statusCode = 404;
9
+ this.name = 'rout_not_found';
10
+ Object.setPrototypeOf(this, NotFoundError.prototype);
11
+ }
12
+ serializeErrors() {
13
+ return {
14
+ message: 'Rout Not Found',
15
+ name: 'rout_not_found',
16
+ };
17
+ }
18
+ }
19
+ exports.NotFoundError = NotFoundError;
@@ -0,0 +1,22 @@
1
+ import { ValidationError } from 'joi';
2
+ import { Response } from 'express';
3
+ import { CustomError } from './custom-error';
4
+ export declare class RequestValidationError extends CustomError {
5
+ errors: ValidationError;
6
+ private res;
7
+ statusCode: number;
8
+ name: string;
9
+ constructor(errors: ValidationError, res: Response);
10
+ serializeErrors(): {
11
+ message: string;
12
+ name: string;
13
+ errors: {
14
+ original: any;
15
+ details: {
16
+ message: string;
17
+ type: string;
18
+ field: string;
19
+ }[];
20
+ };
21
+ };
22
+ }
@@ -0,0 +1,29 @@
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, res) {
7
+ super('validation error');
8
+ this.errors = errors;
9
+ this.res = res;
10
+ this.statusCode = 400;
11
+ this.name = 'validation_error';
12
+ Object.setPrototypeOf(this, RequestValidationError.prototype);
13
+ }
14
+ serializeErrors() {
15
+ return {
16
+ message: 'request validation error',
17
+ name: this.name,
18
+ errors: {
19
+ original: this.errors._original,
20
+ details: this.errors.details.map(({ message, type, context, path }) => ({
21
+ message: message.replace(/['"]/g, ''),
22
+ type,
23
+ field: path.toString(),
24
+ })),
25
+ },
26
+ };
27
+ }
28
+ }
29
+ exports.RequestValidationError = RequestValidationError;
@@ -0,0 +1,14 @@
1
+ import { CustomError } from './custom-error';
2
+ export declare enum NotFoundCustomErrorEnum {
3
+ userNotFound = "user_not_found"
4
+ }
5
+ export declare class NotFoundCustomError extends CustomError {
6
+ message: string;
7
+ name: string;
8
+ statusCode: number;
9
+ constructor(message: string, name: string);
10
+ serializeErrors(): {
11
+ message: string;
12
+ name: string;
13
+ };
14
+ }
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NotFoundCustomError = exports.NotFoundCustomErrorEnum = void 0;
4
+ const custom_error_1 = require("./custom-error");
5
+ var NotFoundCustomErrorEnum;
6
+ (function (NotFoundCustomErrorEnum) {
7
+ NotFoundCustomErrorEnum["userNotFound"] = "user_not_found";
8
+ })(NotFoundCustomErrorEnum || (exports.NotFoundCustomErrorEnum = NotFoundCustomErrorEnum = {}));
9
+ class NotFoundCustomError extends custom_error_1.CustomError {
10
+ constructor(message, name) {
11
+ super(message);
12
+ this.message = message;
13
+ this.name = name;
14
+ this.statusCode = 404;
15
+ Object.setPrototypeOf(this, NotFoundCustomError.prototype);
16
+ }
17
+ serializeErrors() {
18
+ return {
19
+ message: this.message,
20
+ name: this.name,
21
+ };
22
+ }
23
+ }
24
+ exports.NotFoundCustomError = NotFoundCustomError;
@@ -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
+ protected client: Stan;
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,32 @@
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; //5 seconds
7
+ this.client = client;
8
+ }
9
+ subscriptionOptions() {
10
+ return this.client
11
+ .subscriptionOptions()
12
+ .setDeliverAllAvailable()
13
+ .setManualAckMode(true)
14
+ .setAckWait(this.ackWait)
15
+ .setDurableName(this.queueGroupName);
16
+ }
17
+ listen() {
18
+ const subscription = this.client.subscribe(this.subject, this.queueGroupName, this.subscriptionOptions());
19
+ subscription.on('message', (msg) => {
20
+ console.log(`Message received: ${this.subject} / ${this.queueGroupName}`);
21
+ const parsedData = this.parseMessage(msg);
22
+ this.onMessage(parsedData, msg);
23
+ });
24
+ }
25
+ parseMessage(msg) {
26
+ const data = msg.getData();
27
+ return typeof data === 'string'
28
+ ? JSON.parse(data)
29
+ : JSON.parse(data.toString('utf-8'));
30
+ }
31
+ }
32
+ 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
+ protected client: Stan;
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 published to subject', this.subject);
15
+ resolve();
16
+ });
17
+ });
18
+ }
19
+ }
20
+ exports.Publisher = Publisher;
@@ -0,0 +1,3 @@
1
+ export declare enum Subjects {
2
+ UserCreated = "user:created"
3
+ }
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Subjects = void 0;
4
+ var Subjects;
5
+ (function (Subjects) {
6
+ Subjects["UserCreated"] = "user:created";
7
+ })(Subjects || (exports.Subjects = Subjects = {}));
@@ -0,0 +1,12 @@
1
+ import { Subjects } from "../subjects";
2
+ export interface UserCreatedEvent {
3
+ subject: Subjects.UserCreated;
4
+ data: {
5
+ id: string;
6
+ email?: string;
7
+ username?: string;
8
+ mobile?: string;
9
+ name?: string;
10
+ family?: string;
11
+ };
12
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -4,8 +4,10 @@ export * from './errors/not-authorized-error';
4
4
  export * from './errors/notfound';
5
5
  export * from './errors/request-validation-error';
6
6
  export * from './errors/user-not-found-error';
7
-
8
7
  export * from './middlewares/current-user';
9
8
  export * from './middlewares/error-handler';
10
9
  export * from './middlewares/require-auth';
11
-
10
+ export * from './events/base-listener';
11
+ export * from './events/base-publisher';
12
+ export * from './events/subjects';
13
+ export * from './events/user/user-created-event';
package/build/index.js ADDED
@@ -0,0 +1,29 @@
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/not-authorized-error"), exports);
20
+ __exportStar(require("./errors/notfound"), exports);
21
+ __exportStar(require("./errors/request-validation-error"), exports);
22
+ __exportStar(require("./errors/user-not-found-error"), exports);
23
+ __exportStar(require("./middlewares/current-user"), exports);
24
+ __exportStar(require("./middlewares/error-handler"), exports);
25
+ __exportStar(require("./middlewares/require-auth"), exports);
26
+ __exportStar(require("./events/base-listener"), exports);
27
+ __exportStar(require("./events/base-publisher"), exports);
28
+ __exportStar(require("./events/subjects"), exports);
29
+ __exportStar(require("./events/user/user-created-event"), exports);
@@ -0,0 +1,16 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ interface UserPayload {
3
+ _id: string;
4
+ email: string;
5
+ username: string;
6
+ mobile: string;
7
+ }
8
+ declare global {
9
+ namespace Express {
10
+ interface Request {
11
+ currentUser?: UserPayload;
12
+ }
13
+ }
14
+ }
15
+ export declare const currentUser: (req: Request, res: Response, next: NextFunction) => void;
16
+ export {};
@@ -0,0 +1,20 @@
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.currentUser = void 0;
7
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
+ const currentUser = (req, res, next) => {
9
+ var _a;
10
+ if (!((_a = req.session) === null || _a === void 0 ? void 0 : _a.jwt)) {
11
+ return next();
12
+ }
13
+ try {
14
+ const payload = jsonwebtoken_1.default.verify(req.session.jwt, process.env.JWT_KEY);
15
+ req.currentUser = payload;
16
+ }
17
+ catch (err) { }
18
+ next();
19
+ };
20
+ exports.currentUser = currentUser;
@@ -0,0 +1,2 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ export declare const errorHandler: (err: Error, req: Request, res: Response, next: NextFunction) => void;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.errorHandler = void 0;
4
+ const custom_error_1 = require("../errors/custom-error");
5
+ const errorHandler = (err, req, res, next) => {
6
+ if (err instanceof custom_error_1.CustomError) {
7
+ console.error('custom error', err.serializeErrors());
8
+ res.status(err.statusCode).send(err.serializeErrors());
9
+ }
10
+ else {
11
+ console.error('error! ', err);
12
+ res.status(500).send({
13
+ message: 'Something went wrong!',
14
+ });
15
+ }
16
+ };
17
+ exports.errorHandler = errorHandler;
@@ -0,0 +1,2 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ export declare const requireAuth: (req: Request, res: Response, next: NextFunction) => void;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requireAuth = void 0;
4
+ const not_authorized_error_1 = require("../errors/not-authorized-error");
5
+ const requireAuth = (req, res, next) => {
6
+ if (!req.currentUser) {
7
+ throw new not_authorized_error_1.NotAuthorizedError();
8
+ }
9
+ next();
10
+ };
11
+ exports.requireAuth = requireAuth;
package/package.json CHANGED
@@ -1,7 +1,11 @@
1
1
  {
2
2
  "name": "@common_ch/common",
3
- "version": "1.0.4",
4
- "main": "index.js",
3
+ "version": "1.0.6",
4
+ "main": "./build/index.js",
5
+ "types": "./build/index.d.ts",
6
+ "files": [
7
+ "./build/**/*"
8
+ ],
5
9
  "scripts": {
6
10
  "clean": "del ./build/*",
7
11
  "build": "npm run clean && tsc",
@@ -22,6 +26,7 @@
22
26
  "cookie-session": "^2.1.0",
23
27
  "express": "^4.21.2",
24
28
  "joi": "^17.13.3",
25
- "jsonwebtoken": "^9.0.2"
29
+ "jsonwebtoken": "^9.0.2",
30
+ "node-nats-streaming": "^0.3.2"
26
31
  }
27
32
  }
@@ -1,14 +0,0 @@
1
- import { CustomError } from './custom-error';
2
-
3
- export class BadRequestError extends CustomError {
4
- statusCode = 400;
5
- name = 'bad_request_error';
6
- constructor(public message: string) {
7
- super(message);
8
-
9
- Object.setPrototypeOf(this, BadRequestError.prototype);
10
- }
11
- serializeErrors() {
12
- return { message: this.message, name: this.name };
13
- }
14
- }
@@ -1,22 +0,0 @@
1
- export const optionsValidation = { abortEarly: false, allowUnknown: false, stripUnknown: false };
2
-
3
- export interface ValidationError {
4
- message: string;
5
- type: string;
6
- }
7
-
8
- export interface JoiError {
9
- original: unknown;
10
- details: ValidationError[];
11
- }
12
-
13
- export abstract class CustomError extends Error {
14
- abstract statusCode: number;
15
- abstract name: string;
16
- constructor(message: string) {
17
- super(message);
18
- Object.setPrototypeOf(this, CustomError.prototype);
19
- }
20
-
21
- abstract serializeErrors(): { message: string; name: string; errors?: JoiError };
22
- }
@@ -1,13 +0,0 @@
1
- import { CustomError } from './custom-error';
2
-
3
- export class NotAuthorizedError extends CustomError {
4
- statusCode = 401;
5
- name = 'not-authorized-error';
6
- constructor() {
7
- super('Not authorized');
8
- Object.setPrototypeOf(this, NotAuthorizedError.prototype);
9
- }
10
- serializeErrors() {
11
- return { message: 'Not authorized', name: this.name };
12
- }
13
- }
@@ -1,18 +0,0 @@
1
- import { CustomError } from './custom-error';
2
-
3
- export class NotFoundError extends CustomError {
4
- statusCode = 404;
5
- name = 'rout_not_found';
6
- constructor() {
7
- super('Rout Not Found');
8
-
9
- Object.setPrototypeOf(this, NotFoundError.prototype);
10
- }
11
-
12
- serializeErrors() {
13
- return {
14
- message: 'Rout Not Found',
15
- name: 'rout_not_found',
16
- };
17
- }
18
- }
@@ -1,28 +0,0 @@
1
- import { ValidationError } from 'joi';
2
- import { Response } from 'express';
3
- import { CustomError } from './custom-error';
4
-
5
- export class RequestValidationError extends CustomError {
6
- statusCode = 400;
7
- name = 'validation_error'
8
- constructor(public errors: ValidationError, private res: Response) {
9
- super('validation error');
10
-
11
- Object.setPrototypeOf(this, RequestValidationError.prototype);
12
- }
13
-
14
- serializeErrors() {
15
- return {
16
- message: 'request validation error',
17
- name: this.name,
18
- errors: {
19
- original: this.errors._original,
20
- details: this.errors.details.map(({ message, type, context, path }) => ({
21
- message: message.replace(/['"]/g, ''),
22
- type,
23
- field: path.toString(),
24
- })),
25
- },
26
- };
27
- }
28
- }
@@ -1,20 +0,0 @@
1
- import { CustomError } from './custom-error';
2
-
3
- export enum NotFoundCustomErrorEnum {
4
- userNotFound = 'user_not_found',
5
- }
6
- export class NotFoundCustomError extends CustomError {
7
- statusCode = 404;
8
- constructor(public message: string, public name: string) {
9
- super(message);
10
-
11
- Object.setPrototypeOf(this, NotFoundCustomError.prototype);
12
- }
13
-
14
- serializeErrors() {
15
- return {
16
- message: this.message,
17
- name: this.name,
18
- };
19
- }
20
- }
@@ -1,30 +0,0 @@
1
- import { Request, Response, NextFunction } from 'express';
2
- import jwt from 'jsonwebtoken';
3
-
4
- interface UserPayload {
5
- _id: string;
6
- email: string;
7
- username: string;
8
- mobile: string;
9
- }
10
-
11
- declare global {
12
- namespace Express {
13
- interface Request {
14
- currentUser?: UserPayload;
15
- }
16
- }
17
- }
18
-
19
- export const currentUser = (req: Request, res: Response, next: NextFunction) => {
20
-
21
- if (!req.session?.jwt) {
22
- return next();
23
- }
24
-
25
- try {
26
- const payload = jwt.verify(req.session.jwt, process.env.JWT_KEY!) as UserPayload;
27
- req.currentUser = payload;
28
- } catch (err) {}
29
- next();
30
- };
@@ -1,15 +0,0 @@
1
- import { Request, Response, NextFunction } from 'express';
2
-
3
- import { CustomError } from '../errors/custom-error';
4
-
5
- export const errorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => {
6
- if (err instanceof CustomError) {
7
- console.error('custom error', err.serializeErrors());
8
- res.status(err.statusCode).send(err.serializeErrors());
9
- } else {
10
- console.error('error! ', err);
11
- res.status(500).send({
12
- message: 'Something went wrong!',
13
- });
14
- }
15
- };
@@ -1,11 +0,0 @@
1
- import { Request, Response, NextFunction } from 'express';
2
-
3
- import { NotAuthorizedError } from '../errors/not-authorized-error';
4
-
5
- export const requireAuth = (req: Request, res: Response, next: NextFunction) => {
6
- if (!req.currentUser) {
7
- throw new NotAuthorizedError();
8
- }
9
-
10
- next();
11
- };
package/tsconfig.json DELETED
@@ -1,101 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
-
5
- /* Projects */
6
- // "incremental": true, /* Enable incremental compilation */
7
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
- // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
9
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
10
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
-
13
- /* Language and Environment */
14
- "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
- // "jsx": "preserve", /* Specify what JSX code is generated. */
17
- // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
20
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
22
- // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
23
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
-
26
- /* Modules */
27
- "module": "commonjs", /* Specify what module code is generated. */
28
- // "rootDir": "./", /* Specify the root folder within your source files. */
29
- // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
30
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
31
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
32
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
33
- // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
34
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
35
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
36
- // "resolveJsonModule": true, /* Enable importing .json files */
37
- // "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
38
-
39
- /* JavaScript Support */
40
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
41
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
42
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
43
-
44
- /* Emit */
45
- "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
46
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
47
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
48
- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
49
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
50
- "outDir": "./build", /* Specify an output folder for all emitted files. */
51
- // "removeComments": true, /* Disable emitting comments. */
52
- // "noEmit": true, /* Disable emitting files from a compilation. */
53
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
54
- // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
55
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
56
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
57
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
58
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
59
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
60
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
61
- // "newLine": "crlf", /* Set the newline character for emitting files. */
62
- // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
63
- // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
64
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
65
- // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
66
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
67
- // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
68
-
69
- /* Interop Constraints */
70
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
71
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
72
- "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
73
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
74
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
75
-
76
- /* Type Checking */
77
- "strict": true, /* Enable all strict type-checking options. */
78
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
79
- // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
80
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
81
- // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
82
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
83
- // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
84
- // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
85
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
86
- // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
87
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
88
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
89
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
90
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
91
- // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
92
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
93
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
94
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
95
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
96
-
97
- /* Completeness */
98
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
99
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
100
- }
101
- }