first commit

This commit is contained in:
Swapnil
2024-12-06 01:01:25 +05:30
commit 8a60e520c6
29 changed files with 2595 additions and 0 deletions

53
src/app.ts Normal file
View File

@@ -0,0 +1,53 @@
import requestId from 'request-ip';
import express, { Application, NextFunction, Request, Response } from "express";
import config from "./config/config";
import morgan from "./config/morgan";
import path from 'path';
import ApiError from './utils/helper/ApiError';
import { errorConverter, errorHandler } from './middleware/error';
import logger from './config/logger';
import productRouter from "./routes/productRoutes";
class App {
private app: Application;
constructor() {
this.app = express();
this.initializeMiddlewares();
this.initializeRoutes();
this.initializeErrorHandling();
}
private initializeMiddlewares(): void {
if (config.env !== "test") {
this.app.use(morgan.successHandler);
this.app.use(morgan.errorHandler);
}
this.app.use(requestId.mw());
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.app.use("/public", express.static(path.join(__dirname, "../public")));
}
private initializeRoutes(): void {
this.app.use('/api', productRouter);
// Define our routes
this.app.use((req: Request, res: Response, next: NextFunction) => {
next(new ApiError(404, "Not found"));
})
}
private initializeErrorHandling(): void {
this.app.use(errorConverter);
this.app.use(errorHandler);
}
public listen(port: number): ReturnType<typeof this.app.listen> {
return this.app.listen(port, () => {
logger.info(`Server listening on port ${config.port}`);
logger.info(`Enviorment :- ${config.env}`);
})
}
}
export default new App();

89
src/config/config.ts Normal file
View File

@@ -0,0 +1,89 @@
import dotenv from "dotenv";
import path from "path";
import * as yup from 'yup';
dotenv.config({ path: path.join(__dirname, '../../.env') });
const envVarsSchema = yup.object().shape({
NODE_ENV: yup.string().oneOf(["production", "development", "test"]).required(),
PORT: yup.number().default(3000),
JWT_SECRET: yup.string().required('JWT secret key is required'),
JWT_ACCESS_EXPIRATION_MINUTES: yup.number().default(30).required('minutes after which access tokens expire'),
JWT_REFRESH_EXPIRATION_DAYS: yup.number().default(30).required('days after which refresh tokens expire'),
JWT_RESET_PASSWORD_EXPIRATION_MINUTES: yup.number().default(10).required('minutes after which reset password token expires'),
JWT_VERIFY_EMAIL_EXPIRATION_MINUTES: yup.number().default(10).required('minutes after which verify email token expires'),
// DataBase
DB_USERNAME: yup.string().required('DB Username is required'),
DB_PASSWORD: yup.string().required('DB Password is required'),
DB_DATABASE_NAME: yup.string().required('Database name is required'),
DB_HOSTNAME: yup.string().default('127.0.0.1').required('DB Hostname is required'),
DB_PORT: yup.number().default(3306).required('DB Port is required'),
}).noUnknown(true)
// Validate and prepare the configuration
function getConfig() {
try {
// Validate the environment variables
const envVars = envVarsSchema.validateSync(process.env, {
abortEarly: false, // Validate all fields before throwing errors
stripUnknown: true, // Remove fields not in the schema
});
// Return the validated configuration
return {
env: envVars.NODE_ENV,
port: envVars.PORT,
jwt: {
secret: envVars.JWT_SECRET,
accessExpirationMinutes: envVars.JWT_ACCESS_EXPIRATION_MINUTES,
refreshExpirationDays: envVars.JWT_REFRESH_EXPIRATION_DAYS,
resetPasswordExpirationMinutes: envVars.JWT_RESET_PASSWORD_EXPIRATION_MINUTES,
verifyEmailExpirationMinutes: envVars.JWT_VERIFY_EMAIL_EXPIRATION_MINUTES,
},
database: {
development: {
host: envVars.DB_HOSTNAME,
port: envVars.DB_PORT,
username: envVars.DB_USERNAME,
password: envVars.DB_PASSWORD,
database: envVars.DB_DATABASE_NAME,
logging: false,
},
test: {
host: envVars.DB_HOSTNAME,
port: envVars.DB_PORT,
username: envVars.DB_USERNAME,
password: envVars.DB_PASSWORD,
database: envVars.DB_DATABASE_NAME,
logging: false,
socketPath: "/var/run/mysqld/mysqld.sock",
},
production: {
host: envVars.DB_HOSTNAME,
port: envVars.DB_PORT,
username: envVars.DB_USERNAME,
password: envVars.DB_PASSWORD,
database: envVars.DB_DATABASE_NAME,
logging: false,
socketPath: "/var/run/mysqld/mysqld.sock",
},
},
};
} catch (error: any) {
if (error instanceof yup.ValidationError) {
console.error("Validation Errors:", error.errors.join(", "));
} else {
console.error("Unexpected error during configuration validation:", error);
}
console.error("Server shut down due to incomplete environment variable configuration.");
process.exit(1); // Exit with error code 1
}
}
// Validate and export configuration only if validation succeeds
const config = getConfig();
export default config;

16
src/config/data-source.ts Normal file
View File

@@ -0,0 +1,16 @@
import "reflect-metadata"
import { DataSource } from "typeorm"
import config from "./config"
export const AppDataSource = new DataSource({
type: "mysql",
host: config.database[config.env].host, // Dynamically set host based on environment
port: config.database[config.env].port, // Dynamically set port based on environment
username: config.database[config.env].username, // Dynamically set username
password: config.database[config.env].password, // Dynamically set password
database: config.database[config.env].database, // Dynamically set database
synchronize: true,
entities: ["../entities/**/*.ts"],
migrations: ["../migration/**/*.ts"],
subscribers: [],
})

44
src/config/logger.ts Normal file
View File

@@ -0,0 +1,44 @@
import winston, { Logger, format } from "winston";
import config from "./config";
const logger: Logger = winston.createLogger({
level: config.env === "development" ? "debug" : "info",
format: format.combine(
format.splat(), // Supports string interpolation
format.timestamp(), // Adds timestamp to logs
format.printf((info) => {
const { timestamp, level, message } = info as {
timestamp: string;
level: string;
message?: unknown;
};
return `${timestamp ? new Date(timestamp).toLocaleString() : ""} ${level}: ${message}`;
})
),
transports: [
// Log to console
new winston.transports.Console({
level: config.env === "development" ? "debug" : "info",
stderrLevels: ["error"], // Log errors to stderr
format: format.combine(
format.colorize(), // Adds color for console output
format.printf((info) => `${info.level}: ${info.message}`)
),
}),
// Optional: Log to a file in production
...(config.env === "production"
? [
new winston.transports.File({
filename: "logs/error.log",
level: "error",
}),
new winston.transports.File({
filename: "logs/combined.log",
}),
]
: []),
],
});
export default logger;

28
src/config/morgan.ts Normal file
View File

@@ -0,0 +1,28 @@
import { Request, Response } from "express";
import requestId from "request-ip";
import morgan from "morgan";
import config from "./config";
import logger from "./logger";
morgan.token('clientId', (req: Request) => requestId.getClientIp(req) || "");
morgan.token('message', (req: Request, res: Response) => res.locals.errorMessage || "");
// Formats based on environment
const ipFormat = config.env === 'production' ? ':clientIp - ' : '';
const successFormat = `${ipFormat}:method :url :status - :response-time ms`;
const errorFormat = `${ipFormat}:method :url :status - :response-time ms - message: :message`;
// Handlers
const successHandler = morgan(successFormat, {
skip: (req: Request, res: Response) => res.statusCode >= 400,
stream: { write: (msg) => logger.info(msg.trim()) },
});
const errorHandler = morgan(errorFormat, {
skip: (req: Request, res: Response) => res.statusCode < 400,
stream: { write: (msg) => logger.error(msg.trim()) },
});
export default {
successHandler, errorHandler,
}

View File

@@ -0,0 +1,37 @@
import { NextFunction, Request, Response } from 'express';
import { IProductInteractor } from '../interfaces/IProductInteractor';
import { AsyncHandler } from '../utils/handler/AsyncHandler';
import ApiResponse from '../utils/helper/ApiResponse';
export class ProductController {
private interactor: IProductInteractor;
constructor(interactor: IProductInteractor) {
this.interactor = interactor;
}
// @AsyncHandler()
async onCreateProduct(req: Request, res: Response, next: NextFunction) {
const data = await this.interactor.createProduct(req.body);
res.status(201).json(new ApiResponse(201, data, 'Successfully created'));
}
// @AsyncHandler()
async onGetProducts(req: Request, res: Response, next: NextFunction) {
const offset = parseInt(`${req.query.offset}`) || 0;
const limit = parseInt(`${req.query.limit}`) || 10;
const data = await this.interactor.getProducts(limit, offset);
if (data.length === 0) {
res.status(204).json(new ApiResponse(204, null, 'No products found'));
}
res.status(200).json(new ApiResponse(200, data, 'Products retrieved successfully'));
}
// @AsyncHandler()
async onUpdateStock(req: Request, res: Response, next: NextFunction) {
const data = await this.interactor.updateStock(parseInt(`${req.params.id}`), parseInt(`${req.body.stock}`));
res.status(200).json(new ApiResponse(200, data, 'Successfully updated'));
}
}

20
src/entities/Product.ts Normal file
View File

@@ -0,0 +1,20 @@
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class Product {
@PrimaryGeneratedColumn()
id!: number;
@Column()
name!: string
@Column()
description!: string
@Column()
price!: number
@Column()
stock!: number
}

18
src/entities/User.ts Normal file
View File

@@ -0,0 +1,18 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id!: number
@Column()
firstName!: string
@Column()
lastName!: string
@Column()
age!: number
}

43
src/index.ts Normal file
View File

@@ -0,0 +1,43 @@
import app from "./app";
import config from "./config/config";
import { AppDataSource } from "./config/data-source";
import logger from "./config/logger";
let server: ReturnType<typeof app.listen>;
AppDataSource.initialize()
.then(() => {
server = app.listen(config.port)
logger.info("Data Source has been initialized!")
})
.catch((err: Error) => {
logger.error("Error during Data Source initialization", err)
process.exit(1)
})
const exitHandler = () => {
if (server) {
server.close(() => {
logger.info('server closed')
process.exit(1)
})
} else {
process.exit(1)
}
}
const unexpectedErrorHandler = (error: Error) => {
logger.error("Un-Expected Error: ", error)
exitHandler()
}
process.on('uncaughtException', unexpectedErrorHandler)
process.on('unhandledRejection', unexpectedErrorHandler)
process.on('SIGALRM', () => {
logger.info('SIGALRM signal received')
if (server) {
server.close()
}
})

View File

@@ -0,0 +1,23 @@
import { Product } from "../entities/Product";
import { IProductInteractor } from "../interfaces/IProductInteractor";
import { IProductRepository } from "../interfaces/IProductRepository";
export class ProductInteractor implements IProductInteractor {
private repository: IProductRepository
constructor(respository: IProductRepository) {
this.repository = respository
}
async createProduct(input: any): Promise<Product> {
return await this.repository.create(input)
}
async updateStock(id: number, stock: number): Promise<Product> {
return await this.repository.update(id, { stock: stock })
}
async getProducts(limit: number, offset: number): Promise<Product[]> {
return await this.repository.find(limit, offset)
}
}

View File

@@ -0,0 +1,7 @@
import { Product } from "../entities/Product";
export interface IProductInteractor {
createProduct(input: any): Promise<Product>;
updateStock(id: number, stock: number): Promise<Product>;
getProducts(limit: number, offset: number): Promise<Product[]>;
}

View File

@@ -0,0 +1,7 @@
import { Product } from "../entities/Product";
export interface IProductRepository {
create(data: Product): Promise<Product>;
update(id: number, data: Partial<Product>): Promise<Product>;
find(limit: number, offset: number): Promise<Product[]>;
}

61
src/middleware/error.ts Normal file
View File

@@ -0,0 +1,61 @@
import { Request, Response, NextFunction } from 'express';
import ApiError from '../utils/helper/ApiError';
import config from '../config/config';
// Middleware to convert different error types to ApiError
export const errorConverter = (
err: any, // Use a broad type to handle various error types
req: Request,
res: Response,
next: NextFunction
): void => {
let error = err;
if (!(err instanceof ApiError)) {
// Handle all other errors
const statusCode =
err.statusCode
? 400
: 500;
const message = err.message || "Internal Server Error";
error = new ApiError(statusCode, message, [err.message], false, err.stack);
}
next(error);
};
// Middleware to handle errors and send responses
export const errorHandler = (
err: ApiError,
req: Request,
res: Response,
next: NextFunction
): void => {
// Determine the status code and message
let { statusCode, message } = err;
if (config.env === 'production' && !err.isOperational) {
// Hide sensitive error details in production
statusCode = 500;
message = "Internal Server Error" as string;
}
// Attach the error message to response locals for debugging
res.locals.errorMessage = err.message;
// Construct the response object
const response = {
code: statusCode,
message,
...(config.env === 'development' && { stack: err.stack }), // Include stack trace in development
};
// Log the error in development mode
if (config.env === 'development') {
console.error(err.stack || err.message);
}
// Send the error response
res.status(statusCode).json(response);
};

View File

@@ -0,0 +1,41 @@
import { Repository } from "typeorm";
import { AppDataSource } from "../config/data-source";
import { Product } from "../entities/Product";
import { IProductRepository } from "../interfaces/IProductRepository";
import ApiError from "../utils/helper/ApiError";
export class ProductRepository implements IProductRepository {
private readonly productRepository: Repository<Product>;
constructor() {
this.productRepository = AppDataSource.getRepository(Product);
}
// Create a new product
async create(data: Product): Promise<Product> {
const product = this.productRepository.create(data); // Prepare new product entity
return await this.productRepository.save(product); // Save to the database
}
// Update a product
async update(id: number, data: Partial<Product>): Promise<Product> {
// Check if the product exists before updating
const existingProduct = await this.productRepository.findOne({ where: { id } });
if (!existingProduct) {
throw new ApiError(404, `Product with ID ${id} not found`);
}
// Update the product and return the updated entity
await this.productRepository.update(id, data);
return this.productRepository.findOneOrFail({ where: { id } });
}
// Find products with pagination
async find(limit: number, offset: number): Promise<Product[]> {
return await this.productRepository.find({
take: limit,
skip: offset,
order: { id: "ASC" }, // Optional: Add sorting for consistent results
});
}
}

View File

@@ -0,0 +1,17 @@
import express from 'express';
import { ProductController } from '../controllers/productController';
import { ProductRepository } from '../repositories/productRepository';
import { ProductInteractor } from '../interactors/productInteractor';
import { IProductInteractor } from '../interfaces/IProductInteractor';
const repository = new ProductRepository()
const interactor: IProductInteractor = new ProductInteractor(repository)
const productController = new ProductController(interactor);
const router = express.Router();
router.post('/products', productController.onCreateProduct.bind(productController));
router.get('/products', productController.onGetProducts.bind(productController));
router.patch('/products/:id', productController.onUpdateStock.bind(productController));
export default router;

View File

@@ -0,0 +1,15 @@
import { Request, Response, NextFunction } from 'express';
export function AsyncHandler() {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
): void {
const originalMethod = descriptor.value;
descriptor.value = function (req: Request, res: Response, next: NextFunction) {
Promise.resolve(originalMethod.call(this, req, res, next)).catch(next);
};
};
}

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ApiError extends Error {
constructor(statusCode, message = 'Something went wrong', errors = [], isOperational = true, stack = '') {
super(message);
this.statusCode = statusCode;
this.data = null;
this.message = message;
this.success = false;
this.errors = errors;
this.isOperational = isOperational;
if (stack) {
this.stack = stack;
}
else {
Error.captureStackTrace(this, this.constructor);
}
}
}
exports.default = ApiError;
//# sourceMappingURL=ApiError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ApiError.js","sourceRoot":"","sources":["ApiError.ts"],"names":[],"mappings":";;AAAA,MAAM,QAAkB,SAAQ,KAAK;IASjC,YACI,UAAkB,EAClB,UAAkB,sBAAsB,EACxC,SAAqB,EAAE,EACvB,gBAAyB,IAAI,EAC7B,QAAgB,EAAE;QAElB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QAEnC,IAAI,KAAK,EAAE;YACP,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;SACtB;aAAM;YACH,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;SACnD;IACL,CAAC;CACJ;AACD,kBAAe,QAAQ,CAAC"}

View File

@@ -0,0 +1,32 @@
class ApiError<T = any> extends Error {
statusCode: number;
data: T | null;
message: string;
success: boolean;
errors: Array<any>;
isOperational: boolean;
stack?: string;
constructor(
statusCode: number,
message: string = 'Something went wrong',
errors: Array<any> = [],
isOperational: boolean = true,
stack: string = ''
) {
super(message);
this.statusCode = statusCode;
this.data = null;
this.message = message;
this.success = false;
this.errors = errors;
this.isOperational = isOperational;
if (stack) {
this.stack = stack;
} else {
Error.captureStackTrace(this, this.constructor);
}
}
}
export default ApiError;

View File

@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ApiResponse {
constructor(statusCode, data, message = 'Success') {
this.statusCode = statusCode;
this.data = data;
this.message = message;
this.success = statusCode < 400;
}
}
exports.default = ApiResponse;
//# sourceMappingURL=ApiResponse.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ApiResponse.js","sourceRoot":"","sources":["ApiResponse.ts"],"names":[],"mappings":";;AAAA,MAAM,WAAW;IAMb,YAAY,UAAkB,EAAE,IAAc,EAAE,UAAkB,SAAS;QACvE,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,UAAU,GAAG,GAAG,CAAC;IACpC,CAAC;CACJ;AAED,kBAAe,WAAW,CAAC"}

View File

@@ -0,0 +1,15 @@
class ApiResponse<T> {
statusCode: number;
data: T | null;
message: string;
success: boolean;
constructor(statusCode: number, data: T | null, message: string = 'Success') {
this.statusCode = statusCode;
this.data = data;
this.message = message;
this.success = statusCode < 400;
}
}
export default ApiResponse;