1- class CategoriesController { }
1+ const { Category } = require ( '../models' ) ;
2+ const CategoryDao = require ( '../dao/categorie' ) ;
23
3- module . exports = CategoriesController ;
4+ class CategoriesController {
5+ static async post ( req , res , next ) {
6+ try {
7+ const { name, description, image } = req . body ;
8+ const category = await Category . create ( {
9+ name,
10+ description,
11+ image,
12+ } ) ;
13+ category
14+ ? res . status ( 200 ) . json ( { msg : 'Category created successfully' } )
15+ : res . status ( 404 ) . json ( { msg : 'Error. Category not created.' } ) ;
16+ } catch ( error ) {
17+ next ( error ) ;
18+ }
19+ }
20+ static async deleteCategory ( req , res ) {
21+ const { id } = req . params ;
22+ try {
23+ const where = { id } ;
24+ const categoryDeleted = await CategoryDao . deleteCategory ( where ) ;
25+
26+ if ( categoryDeleted ) {
27+ res . status ( 200 ) . json ( { msg : 'Category deleted successfully' } ) ;
28+ } else {
29+ res . status ( 404 ) . json ( { msg : 'Could not find category' } ) ;
30+ }
31+ } catch ( error ) {
32+ res . status ( 400 ) . json ( error ) ;
33+ }
34+ }
35+ static async getAll ( req , res ) {
36+ try {
37+ const categories = await CategoryDao . filteringCategoryResultsByField ( "name" )
38+ const format = categories . map ( category => category . name )
39+ return res . status ( 200 ) . json ( format )
40+ } catch ( error ) {
41+ return res . status ( 500 ) . send ( error )
42+ }
43+ }
44+ static async updateCategory ( req , res ) {
45+ const { id } = req . params ;
46+ const { name, description, image } = req . body ;
47+ try {
48+ const categoryUpdated = await Category . findByPk ( id ) ;
49+ categoryUpdated &&
50+ ( await categoryUpdated . update ( { name, description, image } ) ) ;
51+ categoryUpdated
52+ ? res . status ( 200 ) . json ( { msg : 'Category updated successfully' } )
53+ : res . status ( 404 ) . json ( { msg : 'Could not find category' } ) ;
54+ } catch ( error ) {
55+ res . status ( 400 ) . json ( error ) ;
56+ }
57+ }
58+ }
59+
60+ module . exports = CategoriesController ;
0 commit comments