1+ import slugify from "slugify" ;
2+ import { catchAsyncError } from "../../utils/catch_async_error" ;
3+ import { AppError } from "../../utils/app_error" ;
4+ import { deleteOne } from '../../handler/factor' ;
5+ import { productModel } from "../../models/product_model" ;
6+ import { ApiFeatures } from '../../utils/api_feature' ;
7+
8+
9+ const addProduct = catchAsyncError ( async ( req , res , next ) => {
10+ req . body . imgCover = req . files . imgCover [ 0 ] . filename ;
11+ req . body . images = req . files . images . map ( ( ele ) => ele . filename ) ;
12+
13+ req . body . slug = slugify ( req . body . title ) ;
14+ const addProduct = new productModel ( req . body ) ;
15+ await addProduct . save ( ) ;
16+
17+ res . status ( 201 ) . json ( { message : "success" , addProduct } ) ;
18+ } ) ;
19+
20+ const getAllProducts = catchAsyncError ( async ( req , res , next ) => {
21+ let apiFeature = new ApiFeatures ( productModel . find ( ) , req . query )
22+ . pagination ( )
23+ . fields ( )
24+ . filteration ( )
25+ . search ( )
26+ . sort ( ) ;
27+ const PAGE_NUMBER = apiFeature . queryString . page * 1 || 1 ;
28+ const getAllProducts = await apiFeature . mongooseQuery ;
29+
30+ res
31+ . status ( 201 )
32+ . json ( { page : PAGE_NUMBER , message : "success" , getAllProducts } ) ;
33+ } ) ;
34+ const getSpecificProduct = catchAsyncError ( async ( req , res , next ) => {
35+ const { id } = req . params ;
36+ const getSpecificProduct = await productModel . findByIdAndUpdate ( id ) ;
37+ res . status ( 201 ) . json ( { message : "success" , getSpecificProduct } ) ;
38+ } ) ;
39+
40+ const updateProduct = catchAsyncError ( async ( req , res , next ) => {
41+ const { id } = req . params ;
42+ if ( req . body . title ) {
43+ req . body . slug = slugify ( req . body . title ) ;
44+ }
45+ const updateProduct = await productModel . findByIdAndUpdate ( id , req . body , {
46+ new : true ,
47+ } ) ;
48+
49+ updateProduct && res . status ( 201 ) . json ( { message : "success" , updateProduct } ) ;
50+
51+ ! updateProduct && next ( new AppError ( "Product was not found" , 404 ) ) ;
52+ } ) ;
53+
54+ const deleteProduct = deleteOne ( productModel , "Product" ) ;
55+ export {
56+ addProduct ,
57+ getAllProducts ,
58+ getSpecificProduct ,
59+ updateProduct ,
60+ deleteProduct ,
61+ } ;
0 commit comments