ecomm/__tests__/controllers/ProductController.test.ts
2023-06-13 16:10:17 +03:00

58 lines
1.8 KiB
TypeScript

import { Request, Response } from 'express';
import { Product, IProduct } from '../mongoose/Schema';
export async function createProduct(req: Request, res: Response) {
try {
const { name, description, price, userId } = req.body;
if(!name || !description || !price || !userId) {
res.status(400).json({ error: 'Name, description, price are required.' });
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: userId,
});
res.status(201).json(product);
} catch (error) {
console.error('Error creating product:', error);
res.status(500).json({ error: 'An error occurred while creating the product.' });
}
}
export async function listProducts(req: Request, res: Response) {
try {
const { page, limit } = req.query;
const dbPage = Number(page) || 0;
const dbLimit = Number(limit) || 50;
const products = await Product.find().sort({ price: 1 }).skip(Number(dbPage) * Number(dbLimit)).limit(Number(dbLimit));
res.json(products);
} catch (error) {
console.error('Error listing products:', error);
res.status(500).json({ error: 'An error occurred while listing the products.' });
}
}
export async function getProduct(req: Request, res: Response) {
const { id } = req.params;
try {
const product = await Product.findById(id);
if(!product) {
res.status(404).json({ error: 'Product not found.' });
return;
}
res.json(product);
} catch (error) {
console.error('Error getting product:', error);
res.status(404).json({ error: 'Product not found.' });
}
}