@mainshopapp/common 1.0.1

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,11 @@
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
+ }
@@ -0,0 +1,19 @@
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
+ return { message: err.msg, field: err.param };
16
+ });
17
+ }
18
+ }
19
+ exports.RequestValidationError = RequestValidationError;
@@ -0,0 +1,11 @@
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 './middlewares/error-handler';
8
+ export * from './middlewares/require-auth';
9
+ export * from './middlewares/validate-request';
10
+ export * from './middlewares/current-user';
11
+ export * from './middlewares/uploader';
package/build/index.js ADDED
@@ -0,0 +1,34 @@
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("./middlewares/error-handler"), exports);
24
+ __exportStar(require("./middlewares/require-auth"), exports);
25
+ __exportStar(require("./middlewares/validate-request"), exports);
26
+ __exportStar(require("./middlewares/current-user"), exports);
27
+ __exportStar(require("./middlewares/uploader"), exports);
28
+ // export * from './constants/auth/user.interfaces'
29
+ // export * from './services/authentication.service'
30
+ // export * from './constants/globals';
31
+ // export * from './constants/seller/product.interfaces'
32
+ // export * from './constants/buyer/cart-product.inerfaces'
33
+ // export * from './constants/buyer/cart.interfaces'
34
+ // export * from './constants/buyer/order.interfaces'
@@ -0,0 +1,9 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ declare global {
3
+ interface Req extends Request {
4
+ session?: any;
5
+ currentUser?: any;
6
+ uploaderError?: Error;
7
+ }
8
+ }
9
+ export declare const currentUser: (jwt_key: string) => (req: Req, res: Response, next: NextFunction) => void;
@@ -0,0 +1,24 @@
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 = (jwt_key) => {
9
+ return (req, res, next) => {
10
+ var _a;
11
+ if (!((_a = req.session) === null || _a === void 0 ? void 0 : _a.jwt)) {
12
+ return next();
13
+ }
14
+ try {
15
+ const payload = jsonwebtoken_1.default.verify(req.session.jwt, jwt_key);
16
+ req.currentUser = payload;
17
+ }
18
+ catch (err) {
19
+ next(err);
20
+ }
21
+ next();
22
+ };
23
+ };
24
+ exports.currentUser = currentUser;
@@ -0,0 +1,2 @@
1
+ import { Response, NextFunction } from 'express';
2
+ export declare const errorHandler: (err: Error, req: Req, res: Response, next: NextFunction) => Response<any, Record<string, any>> | undefined;
@@ -0,0 +1,14 @@
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
+ return res.status(err.statusCode).send({ errors: err.serializeErrors() });
8
+ }
9
+ console.error(err);
10
+ res.status(400).send({
11
+ errors: [{ message: 'Something went wrong' }],
12
+ });
13
+ };
14
+ exports.errorHandler = errorHandler;
@@ -0,0 +1,2 @@
1
+ import { Response, NextFunction } from 'express';
2
+ export declare const requireAuth: (req: Req, 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;
@@ -0,0 +1,14 @@
1
+ import multer, { FileFilterCallback } from "multer";
2
+ export interface UploaderMiddlewareOptions {
3
+ types?: string[];
4
+ fieldName?: string;
5
+ }
6
+ export declare class Uploader {
7
+ uploadDir?: string | undefined;
8
+ fileFilter: (types?: Array<string>) => (req: Req, file: Express.Multer.File, cb: FileFilterCallback) => void;
9
+ storage: multer.StorageEngine;
10
+ defaultUploadDir: string;
11
+ constructor(uploadDir?: string | undefined);
12
+ uploadMultipleFiles(options: UploaderMiddlewareOptions): import("express").RequestHandler<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>;
13
+ uploadSingleFile(options: UploaderMiddlewareOptions): import("express").RequestHandler<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>;
14
+ }
@@ -0,0 +1,46 @@
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.Uploader = void 0;
7
+ const multer_1 = __importDefault(require("multer"));
8
+ class Uploader {
9
+ constructor(uploadDir) {
10
+ this.uploadDir = uploadDir;
11
+ this.fileFilter = (types) => {
12
+ return (req, file, cb) => {
13
+ const type = file.mimetype;
14
+ if (!types)
15
+ return cb(null, true);
16
+ if (types.length === 0)
17
+ return cb(null, true);
18
+ if (types.some((accepted) => type === accepted)) {
19
+ return cb(null, true);
20
+ }
21
+ else {
22
+ req.uploaderError = new Error(`we only accept these types: ${types}`);
23
+ return cb(null, false);
24
+ }
25
+ };
26
+ };
27
+ this.storage = multer_1.default.diskStorage({
28
+ destination: (req, file, cb) => {
29
+ cb(null, this.uploadDir || this.defaultUploadDir);
30
+ },
31
+ filename: (req, file, cb) => {
32
+ cb(null, file.fieldname + Date.now());
33
+ }
34
+ });
35
+ this.defaultUploadDir = "upload/";
36
+ }
37
+ uploadMultipleFiles(options) {
38
+ return (0, multer_1.default)({ storage: this.storage, fileFilter: this.fileFilter(options.types) })
39
+ .array(options.fieldName || 'file');
40
+ }
41
+ uploadSingleFile(options) {
42
+ return (0, multer_1.default)({ storage: this.storage, fileFilter: this.fileFilter(options.types) })
43
+ .single(options.fieldName || 'file');
44
+ }
45
+ }
46
+ exports.Uploader = Uploader;
@@ -0,0 +1,2 @@
1
+ import { Response, NextFunction } from 'express';
2
+ export declare const validateRequest: (req: Req, res: Response, next: NextFunction) => void;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateRequest = void 0;
4
+ const express_validator_1 = require("express-validator");
5
+ const request_validation_error_1 = require("../errors/request-validation-error");
6
+ const validateRequest = (req, res, next) => {
7
+ const errors = (0, express_validator_1.validationResult)(req);
8
+ if (!errors.isEmpty()) {
9
+ throw new request_validation_error_1.RequestValidationError(errors.array());
10
+ }
11
+ next();
12
+ };
13
+ exports.validateRequest = validateRequest;
File without changes
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ // import jwt from 'jsonwebtoken'
3
+ // // import { JwtPayload } from '../constants/globals';
4
+ // import { scrypt, randomBytes } from 'crypto'
5
+ // import { promisify } from 'util'
6
+ // const scryptAsync = promisify(scrypt);
7
+ // export class AuthenticationService {
8
+ // generateJwt(payload: JwtPayload, JWT_KEY: string) {
9
+ // return jwt.sign(payload, JWT_KEY);
10
+ // }
11
+ // async pwdToHash(password: string) {
12
+ // const salt = randomBytes(8).toString('hex');
13
+ // const buf = (await scryptAsync(password, salt, 64)) as Buffer
14
+ // return `${buf.toString('hex')}.${salt}`
15
+ // }
16
+ // async pwdCompare(storedPassword: string, suppliedPassword: string) {
17
+ // const [hashedPassword, salt] = storedPassword.split('.');
18
+ // const buf = (await scryptAsync(suppliedPassword, salt, 64)) as Buffer
19
+ // return buf.toString('hex') === hashedPassword;
20
+ // }
21
+ // verifyJwt(jwtToken: string, JWT_KEY: string) {
22
+ // return jwt.verify(jwtToken, JWT_KEY) as JwtPayload
23
+ // }
24
+ // }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@mainshopapp/common",
3
+ "version": "1.0.1",
4
+ "description": "",
5
+ "main": "./build/index.js",
6
+ "types": "./build/index.d.ts",
7
+ "files": [
8
+ "build/**/*"
9
+ ],
10
+ "scripts": {
11
+ "clean": "del ./build/*",
12
+ "build": "npm run clean && tsc",
13
+ "pub": "git add . && git commit -m \"Update\" && npm version patch && npm run build && npm publish"
14
+ },
15
+ "keywords": [],
16
+ "author": "",
17
+ "license": "ISC",
18
+ "dependencies": {
19
+ "@types/express": "^4.17.14",
20
+ "@types/express-validator": "^3.0.0",
21
+ "@types/jsonwebtoken": "^8.5.9",
22
+ "@types/multer": "^1.4.7",
23
+ "express": "^4.18.1",
24
+ "express-validator": "^6.14.2",
25
+ "jsonwebtoken": "^9.0.3",
26
+ "mongoose": "^6.6.1",
27
+ "multer": "^1.4.5-lts.1"
28
+ },
29
+ "devDependencies": {
30
+ "del-cli": "^5.0.0"
31
+ }
32
+ }