1+ import Product from "../models/Product" ;
2+ import User from "../models/User" ;
3+
4+ class ProductController {
5+ async index ( request , response ) {
6+ const products = await Product . find ( ) ;
7+
8+ return response . json ( products ) ;
9+ }
10+
11+ async find ( request , response ) {
12+ const { id } = request . params ;
13+ const result = await Product . find ( { where : { id } } ) ;
14+ const product = result [ 0 ] ;
15+
16+ if ( ! product )
17+ return response . status ( 400 ) . json ( { erro : 'Product not found!' } ) ;
18+
19+ return response . json ( product ) ;
20+ }
21+
22+ async create ( request , response ) {
23+ const { description, user_id } = request . body ;
24+
25+ if ( ! description )
26+ return response . status ( 400 ) . json ( { error : 'Product description can\'t be null' } ) ;
27+
28+ if ( user_id === null )
29+ return response . status ( 400 ) . json ( { error : 'User ID can\'t be null' } ) ;
30+
31+ const result = await User . find ( { where : { id : user_id } } ) ;
32+ const user = result [ 0 ] ;
33+
34+ if ( ! user )
35+ return response . status ( 400 ) . json ( { erro : 'User not found!' } ) ;
36+
37+ const product = await Product . create ( { description, user_id } ) ;
38+
39+ return response . status ( 201 ) . json ( product ) ;
40+ }
41+
42+ async update ( request , response ) {
43+ const { id } = request . params ;
44+ const { description } = request . body ;
45+ const result = await Product . find ( { where : { id } } ) ;
46+ const product = result [ 0 ] ;
47+
48+ if ( ! product )
49+ return response . status ( 400 ) . json ( { error : 'Product not found!' } ) ;
50+
51+ if ( ! description )
52+ return response . status ( 400 ) . json ( { error : 'Product description can\'t be null' } ) ;
53+
54+ await Product . update ( { description } , { where : { id } } ) ;
55+
56+ return response . status ( 204 ) . send ( ) ;
57+ }
58+
59+ async delete ( request , response ) {
60+ const { id } = request . params ;
61+ const result = await Product . find ( { where : { id } } ) ;
62+ const product = result [ 0 ] ;
63+
64+ if ( ! product )
65+ return response . status ( 400 ) . json ( { error : 'Product not found!' } ) ;
66+
67+ await Product . delete ( { where : { id } } ) ;
68+ return response . status ( 204 ) . send ( ) ;
69+ }
70+ }
71+
72+ export default new ProductController ( ) ;
0 commit comments