handeling save product with pre save method and error handlers
This commit is contained in:
parent
62fbfb97b2
commit
9cb00a1162
5 changed files with 43 additions and 25 deletions
|
@ -1,30 +1,16 @@
|
||||||
import { Request, Response } from 'express';
|
import { Request, Response } from 'express';
|
||||||
import { Product, IProduct } from '../schemas/productModel';
|
import { Product, IProduct } from '../schemas/productModel';
|
||||||
|
import { handleCreateProductError } from '../middlewares/errorHandlers';
|
||||||
|
|
||||||
|
|
||||||
export async function createProduct(req: Request, res: Response) {
|
export async function createProduct(req: Request, res: Response) {
|
||||||
try {
|
try {
|
||||||
const { name, description, price, userId } = req.body;
|
const product = new Product(req.body);
|
||||||
if(!name || !description || !price || !userId) {
|
await product.save();
|
||||||
res.status(400).json({ error: 'Name, description, price are required.' });
|
res.json(product);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const productExists = await Product.exists({ name, userId });
|
|
||||||
if(productExists) {
|
|
||||||
res.status(400).json({ error: 'Product already exists.' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const product: IProduct = await Product.create({
|
|
||||||
name,
|
|
||||||
description,
|
|
||||||
price,
|
|
||||||
userId,
|
|
||||||
});
|
|
||||||
|
|
||||||
res.status(201).json(product);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error creating product:', error);
|
console.error('Error creating product:', error);
|
||||||
res.status(500).json({ error: 'An error occurred while creating the product.' });
|
handleCreateProductError(res, error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
18
src/middlewares/errorHandlers.ts
Normal file
18
src/middlewares/errorHandlers.ts
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export function handleCreateProductError(res: Response, error: Error) {
|
||||||
|
let statusCode = 500;
|
||||||
|
let errorMessage = 'An error occurred while creating the product.';
|
||||||
|
|
||||||
|
if (error.message === 'Missing required fields.') {
|
||||||
|
statusCode = 400;
|
||||||
|
errorMessage = 'Missing required fields.';
|
||||||
|
} else if (error.message === 'Product already exists.') {
|
||||||
|
statusCode = 409;
|
||||||
|
errorMessage = 'Product already exists.';
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(statusCode).json({ error: errorMessage });
|
||||||
|
}
|
|
@ -3,8 +3,6 @@ import { authenticateToken } from '../middlewares/checkAuth';
|
||||||
import { addToCart, listCart, checkout, clearCart } from '../controllers/cartController';
|
import { addToCart, listCart, checkout, clearCart } from '../controllers/cartController';
|
||||||
import { checkUuid } from '../middlewares/checkUuid';
|
import { checkUuid } from '../middlewares/checkUuid';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const cartRouter = express.Router();
|
const cartRouter = express.Router();
|
||||||
|
|
||||||
cartRouter.post('/', [authenticateToken], addToCart);
|
cartRouter.post('/', [authenticateToken], addToCart);
|
||||||
|
|
|
@ -1,7 +1,5 @@
|
||||||
import mongoose, { Schema, Document } from 'mongoose';
|
import mongoose, { Schema, Document } from 'mongoose';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
interface IOrder extends Document {
|
interface IOrder extends Document {
|
||||||
userId: string;
|
userId: string;
|
||||||
products: { [itemId: string]: number };
|
products: { [itemId: string]: number };
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
import mongoose, { Schema, Document } from 'mongoose';
|
import mongoose, { Schema, Document } from 'mongoose';
|
||||||
|
import { Request } from 'express';
|
||||||
|
|
||||||
interface IProduct extends Document {
|
interface IProduct extends Document {
|
||||||
name: string;
|
name: string;
|
||||||
|
@ -18,10 +19,27 @@ const ProductSchema: Schema = new Schema({
|
||||||
updatedAt: { type: Date, default: Date.now },
|
updatedAt: { type: Date, default: Date.now },
|
||||||
});
|
});
|
||||||
|
|
||||||
const Product = mongoose.model<IProduct>('Product', ProductSchema);
|
ProductSchema.pre('save', async function (next) {
|
||||||
|
try {
|
||||||
|
if (!this.name || !this.description || !this.price || !this.userId) {
|
||||||
|
throw new Error('Missing required fields.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const productExists = await mongoose.model<IProduct>('Product').exists({ name: this.name, userId: this.userId });
|
||||||
|
if (productExists) {
|
||||||
|
throw new Error('Product already exists.');
|
||||||
|
}
|
||||||
|
|
||||||
|
next();
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const Product = mongoose.model<IProduct>('Product', ProductSchema);
|
||||||
ProductSchema.index({ name: 1, userId: 1 }, { unique: true });
|
ProductSchema.index({ name: 1, userId: 1 }, { unique: true });
|
||||||
|
|
||||||
|
|
||||||
export {
|
export {
|
||||||
Product,
|
Product,
|
||||||
IProduct
|
IProduct
|
||||||
|
|
Loading…
Reference in a new issue