first commit
This commit is contained in:
15
.env
Normal file
15
.env
Normal file
@@ -0,0 +1,15 @@
|
||||
NODE_ENV=
|
||||
PORT=3000
|
||||
|
||||
JWT_SECRET=your_jwt_secret
|
||||
JWT_ACCESS_EXPIRATION_MINUTES=230
|
||||
JWT_REFRESH_EXPIRATION_DAYS=30
|
||||
JWT_RESET_PASSWORD_EXPIRATION_MINUTES=10
|
||||
JWT_VERIFY_EMAIL_EXPIRATION_MINUTES=10
|
||||
|
||||
// DataBase
|
||||
DB_USERNAME=root
|
||||
DB_PASSWORD=root
|
||||
DB_DATABASE_NAME=test
|
||||
DB_HOSTNAME=localhost
|
||||
DB_PORT=3306
|
||||
16
.env.example
Normal file
16
.env.example
Normal file
@@ -0,0 +1,16 @@
|
||||
NODE_ENV=
|
||||
PORT=
|
||||
|
||||
JWT_SECRET=your_jwt_secret
|
||||
JWT_ACCESS_EXPIRATION_MINUTES=230
|
||||
JWT_REFRESH_EXPIRATION_DAYS=30
|
||||
JWT_RESET_PASSWORD_EXPIRATION_MINUTES=10
|
||||
JWT_VERIFY_EMAIL_EXPIRATION_MINUTES=10
|
||||
|
||||
|
||||
// DataBase
|
||||
DB_USERNAME=username
|
||||
DB_PASSWORD=password
|
||||
DB_DATABASE_NAME=database_name
|
||||
DB_HOSTNAME=host
|
||||
DB_PORT=port
|
||||
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
.idea/
|
||||
.vscode/
|
||||
node_modules/
|
||||
build/
|
||||
tmp/
|
||||
temp/
|
||||
7
README.md
Normal file
7
README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
# Awesome Project Build with TypeORM
|
||||
|
||||
Steps to run this project:
|
||||
|
||||
1. Run `npm i` command
|
||||
2. Setup database settings inside `data-source.ts` file
|
||||
3. Run `npm start` command
|
||||
30
package.json
Normal file
30
package.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"dependencies": {
|
||||
"cross-env": "^7.0.3",
|
||||
"dotenv": "^16.4.5",
|
||||
"express": "^4.21.1",
|
||||
"inversify": "^6.1.4",
|
||||
"morgan": "^1.10.0",
|
||||
"mysql": "^2.14.1",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"request-ip": "^3.3.0",
|
||||
"typeorm": "0.3.20",
|
||||
"winston": "^3.17.0",
|
||||
"yup": "^1.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/morgan": "^1.9.9",
|
||||
"@types/node": "^16.11.10",
|
||||
"@types/request-ip": "^0.0.41",
|
||||
"ts-node": "10.9.2",
|
||||
"ts-node-dev": "^2.0.0",
|
||||
"typescript": "4.5.2"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "cross-env NODE_ENV=development nodemon src/index.ts",
|
||||
"start": "ts-node src/index.ts",
|
||||
"build" : "tsc",
|
||||
"typeorm": "cross-env NODE_ENV=development typeorm-ts-node-commonjs"
|
||||
}
|
||||
}
|
||||
53
src/app.ts
Normal file
53
src/app.ts
Normal 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
89
src/config/config.ts
Normal 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
16
src/config/data-source.ts
Normal 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
44
src/config/logger.ts
Normal 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
28
src/config/morgan.ts
Normal 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,
|
||||
}
|
||||
37
src/controllers/productController.ts
Normal file
37
src/controllers/productController.ts
Normal 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
20
src/entities/Product.ts
Normal 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
18
src/entities/User.ts
Normal 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
43
src/index.ts
Normal 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()
|
||||
}
|
||||
})
|
||||
23
src/interactors/productInteractor.ts
Normal file
23
src/interactors/productInteractor.ts
Normal 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)
|
||||
}
|
||||
|
||||
}
|
||||
7
src/interfaces/IProductInteractor.ts
Normal file
7
src/interfaces/IProductInteractor.ts
Normal 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[]>;
|
||||
}
|
||||
7
src/interfaces/IProductRepository.ts
Normal file
7
src/interfaces/IProductRepository.ts
Normal 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
61
src/middleware/error.ts
Normal 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);
|
||||
};
|
||||
|
||||
41
src/repositories/productRepository.ts
Normal file
41
src/repositories/productRepository.ts
Normal 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
|
||||
});
|
||||
}
|
||||
}
|
||||
17
src/routes/productRoutes.ts
Normal file
17
src/routes/productRoutes.ts
Normal 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;
|
||||
15
src/utils/handler/AsyncHandler.ts
Normal file
15
src/utils/handler/AsyncHandler.ts
Normal 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);
|
||||
};
|
||||
};
|
||||
}
|
||||
21
src/utils/helper/ApiError.js
Normal file
21
src/utils/helper/ApiError.js
Normal 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
|
||||
1
src/utils/helper/ApiError.js.map
Normal file
1
src/utils/helper/ApiError.js.map
Normal 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"}
|
||||
32
src/utils/helper/ApiError.ts
Normal file
32
src/utils/helper/ApiError.ts
Normal 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;
|
||||
12
src/utils/helper/ApiResponse.js
Normal file
12
src/utils/helper/ApiResponse.js
Normal 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
|
||||
1
src/utils/helper/ApiResponse.js.map
Normal file
1
src/utils/helper/ApiResponse.js.map
Normal 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"}
|
||||
15
src/utils/helper/ApiResponse.ts
Normal file
15
src/utils/helper/ApiResponse.ts
Normal 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;
|
||||
114
tsconfig.json
Normal file
114
tsconfig.json
Normal file
@@ -0,0 +1,114 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||
|
||||
/* Projects */
|
||||
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||
|
||||
/* Language and Environment */
|
||||
"target": "es6", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
"lib": [
|
||||
"es5",
|
||||
"es6"
|
||||
], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
"experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
||||
"emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||
|
||||
/* Modules */
|
||||
"module": "commonjs", /* Specify what module code is generated. */
|
||||
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
||||
// "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
|
||||
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
||||
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
||||
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
||||
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
|
||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||
|
||||
/* JavaScript Support */
|
||||
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||
|
||||
/* Emit */
|
||||
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||
"sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||
// "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. */
|
||||
"outDir": "./build", /* Specify an output folder for all emitted files. */
|
||||
// "removeComments": true, /* Disable emitting comments. */
|
||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
||||
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||
|
||||
/* Type Checking */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
|
||||
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||
|
||||
/* Completeness */
|
||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||
},
|
||||
}
|
||||
Reference in New Issue
Block a user