1+ import { catchAsyncError } from '../../utils/catch_async_error' ;
2+ import { AppError } from '../../utils/app_error' ;
3+ import { deleteOne } from '../../handler/factor' ;
4+ import { ApiFeatures } from '../../utils/api_feature' ;
5+ import { reviewModel } from '../../models/review_model' ;
6+
7+ const addReview = catchAsyncError ( async ( req , res , next ) => {
8+ req . body . userId = req . user . _id ;
9+ let isReviewed = await reviewModel . findOne ( {
10+ userId : req . user . _id ,
11+ productId : req . body . productId ,
12+ } ) ;
13+ if ( isReviewed ) return next ( new AppError ( "You created a review before" , 409 ) ) ;
14+ const addReview = new reviewModel ( req . body ) ;
15+ await addReview . save ( ) ;
16+
17+ res . status ( 201 ) . json ( { message : "success" , addReview } ) ;
18+ } ) ;
19+
20+ const getAllReviews = catchAsyncError ( async ( req , res , next ) => {
21+ let apiFeature = new ApiFeatures ( reviewModel . find ( ) , req . query )
22+ . pagination ( )
23+ . fields ( )
24+ . filteration ( )
25+ . search ( )
26+ . sort ( ) ;
27+ const PAGE_NUMBER = apiFeature . queryString . page * 1 || 1 ;
28+ const getAllReviews = await apiFeature . mongooseQuery ;
29+ res
30+ . status ( 201 )
31+ . json ( { page : PAGE_NUMBER , message : "success" , getAllReviews } ) ;
32+ } ) ;
33+
34+ const getSpecificReview = catchAsyncError ( async ( req , res , next ) => {
35+ const { id } = req . params ;
36+
37+ let result = await reviewModel . findById ( id ) ;
38+
39+ ! result && next ( new AppError ( "Reveiw was not found" , 404 ) ) ;
40+ result && res . status ( 200 ) . json ( { message : "success" , result } ) ;
41+ } ) ;
42+
43+ const updateReview = catchAsyncError ( async ( req , res , next ) => {
44+ const { id } = req . params ;
45+ console . log ( { user : req . user . _id } ) ;
46+ const updateReview = await reviewModel . findOneAndUpdate (
47+ { _id : id , userId : req . user . _id } ,
48+ req . body ,
49+ {
50+ new : true ,
51+ }
52+ ) ;
53+
54+ console . log ( updateReview ) ;
55+
56+ updateReview && res . status ( 201 ) . json ( { message : "success" , updateReview } ) ;
57+
58+ ! updateReview &&
59+ next (
60+ new AppError (
61+ "Review was not found or you're not authorized to review this project" ,
62+ 404
63+ )
64+ ) ;
65+ } ) ;
66+
67+ const deleteReview = deleteOne ( reviewModel , "Review" ) ;
68+ export {
69+ addReview ,
70+ getAllReviews ,
71+ getSpecificReview ,
72+ updateReview ,
73+ deleteReview ,
74+ } ;
0 commit comments