feat: add bcrypt for password hashing and implement logger utility

This commit is contained in:
2026-01-13 00:18:44 +03:00
parent ae6521977d
commit 64e304214b
11 changed files with 109 additions and 104 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ import cors from "cors";
import morgan from "morgan";
import { errorHandler } from "./middleware/error.middleware.js";
import { authRoutes } from "./routes/auth.routes.js";
import authRoutes from "./routes/auth.routes.js";
import productRoutes from "./routes/product.routes.js";
import orderRoutes from "./routes/order.routes.js";
+2 -2
View File
@@ -1,5 +1,5 @@
import { Request, Response, NextFunction } from "express";
import { AuthService } from "../services/auth.service";
import type { Request, Response, NextFunction } from "express";
import { AuthService } from "../services/auth.service.js";
export class AuthController {
static async register(req: Request, res: Response, next: NextFunction) {
+2 -2
View File
@@ -1,5 +1,5 @@
import { Request, Response, NextFunction } from "express";
import { OrderService } from "../services/order.service";
import type { Request, Response, NextFunction } from "express";
import { OrderService } from "../services/order.service.js";
export class OrderController {
static async create(req: Request, res: Response, next: NextFunction) {
+2 -2
View File
@@ -1,5 +1,5 @@
import { Request, Response, NextFunction } from "express";
import { ProductService } from "../services/product.service";
import type { Request, Response, NextFunction } from "express";
import { ProductService } from "../services/product.service.js";
export class ProductController {
static async create(req: Request, res: Response, next: NextFunction) {
+1 -1
View File
@@ -1,5 +1,5 @@
import { ZodSchema } from "zod";
import { Request, Response, NextFunction } from "express";
import type { Request, Response, NextFunction } from "express";
export const validate =
(schema: ZodSchema) => (req: Request, _res: Response, next: NextFunction) => {
+17 -95
View File
@@ -1,6 +1,6 @@
import mongoose from "mongoose";
import { ProductModel } from "../models/product.model";
import { OrderModel } from "../models/order.model";
import { ProductRepository } from "../repositories/product.repo";
import { OrderRepository } from "../repositories/order.repo";
export class OrderService {
static async createOrder(
@@ -12,28 +12,18 @@ export class OrderService {
try {
const productIds = items.map((i) => i.productId);
const products = await ProductModel.find({
_id: { $in: productIds },
}).session(session);
const products = await ProductRepository.findByIds(productIds, session);
if (products.length !== productIds.length) {
throw { statusCode: 400, message: "One or more products not found" };
}
const orderItems = [];
let total = 0;
const orderItems = [];
for (const item of items) {
const product = products.find((p) => p._id === item.productId)!;
if (item.quantity <= 0) {
throw {
statusCode: 400,
message: "Quantity must be greater than zero",
};
}
if (product.stock < item.quantity) {
throw {
statusCode: 409,
@@ -41,8 +31,11 @@ export class OrderService {
};
}
product.stock -= item.quantity;
await product.save({ session });
await ProductRepository.decrementStock(
product._id,
item.quantity,
session,
);
orderItems.push({
productId: product._id,
@@ -53,87 +46,16 @@ export class OrderService {
total += product.price * item.quantity;
}
const order = await OrderModel.create(
[
{
userId,
items: orderItems,
total,
status: "created",
},
],
{ session },
const order = await OrderRepository.create(
{
userId,
items: orderItems,
total,
status: "created",
},
session,
);
await session.commitTransaction();
return order[0];
} catch (err) {
await session.abortTransaction();
throw err;
} finally {
session.endSession();
}
}
static async listOrders(userId: string, role: "admin" | "customer") {
if (role === "admin") {
return OrderModel.find().lean();
}
return OrderModel.find({ userId }).lean();
}
static async payOrder(orderId: string) {
const order = await OrderModel.findById(orderId);
if (!order) {
throw { statusCode: 404, message: "Order not found" };
}
if (order.status === "paid") {
return order;
}
if (order.status === "cancelled") {
throw { statusCode: 409, message: "Order is cancelled" };
}
order.status = "paid";
await order.save();
return order;
}
static async cancelOrder(orderId: string) {
const session = await mongoose.startSession();
session.startTransaction();
try {
const order = await OrderModel.findById(orderId).session(session);
if (!order) {
throw { statusCode: 404, message: "Order not found" };
}
if (order.status === "cancelled") {
await session.commitTransaction();
return order;
}
if (order.status === "paid") {
throw {
statusCode: 409,
message: "Paid orders cannot be cancelled",
};
}
for (const item of order.items) {
await ProductModel.updateOne(
{ _id: item.productId },
{ $inc: { stock: item.quantity } },
{ session },
);
}
order.status = "cancelled";
await order.save({ session });
await session.commitTransaction();
return order;
} catch (err) {
+22
View File
@@ -0,0 +1,22 @@
type LogMeta = Record<string, unknown>;
function format(level: string, message: string, meta?: LogMeta) {
const timestamp = new Date().toISOString();
return meta
? `[${timestamp}] ${level.toUpperCase()} ${message} ${JSON.stringify(meta)}`
: `[${timestamp}] ${level.toUpperCase()} ${message}`;
}
export const logger = {
info(message: string, meta?: LogMeta) {
console.log(format("info", message, meta));
},
warn(message: string, meta?: LogMeta) {
console.warn(format("warn", message, meta));
},
error(message: string, meta?: LogMeta) {
console.error(format("error", message, meta));
},
};
+14
View File
@@ -0,0 +1,14 @@
import bcrypt from "bcrypt";
const SALT_ROUNDS = 10;
export async function hashPassword(password: string): Promise<string> {
return bcrypt.hash(password, SALT_ROUNDS);
}
export async function verifyPassword(
password: string,
hash: string,
): Promise<boolean> {
return bcrypt.compare(password, hash);
}