ecomm/src/models/productModel.ts

75 lines
1.8 KiB
TypeScript

import { Product } from '../schemas/productSchema';
import { Request, Response } from 'express';
import { ApiError } from '../utils/ApiError';
const createProduct = async (product: any) => {
try {
const newProduct = new Product(product);
const isExist = await Product.findOne({ name: product.name, userId: product.userId });
if(isExist) {
const error = new ApiError('Product already exists');
error.statusCode = 400;
error.status = 'fail';
return error;
}
await newProduct.save();
return newProduct;
} catch {
const error = new ApiError('Error during product creation');
error.statusCode = 500;
error.status = 'fail';
return error;
}
}
const getAllProducts = async (query: {
page: number,
limit: number
}) => {
try {
const { page, limit } = query;
const dbPage = page || 0;
const dbLimit = limit || 50;
const products = await Product.find(null, 'name description price').sort({ price: 1 }).skip(dbPage * dbLimit).limit(dbLimit);
return products;
} catch {
const error = new ApiError('Error during product creation');
error.statusCode = 500;
error.status = 'fail';
return error;
}
}
const getOne = async (id: string) => {
try {
const product = await Product.findById(id, 'name description price');
return product;
} catch {
const error = new ApiError('Product not found');
error.statusCode = 404;
error.status = 'fail';
return error;
}
}
const removeProduct = async (id: string) => {
try {
const product = await Product.findByIdAndDelete(id);
return product;
} catch {
const error = new ApiError('Product not found');
error.statusCode = 404;
error.status = 'fail';
return error;
}
}
export {
createProduct,
getAllProducts,
getOne
}