1+ import { Request , Response } from "express" ;
2+ import { UploadedFile } from 'express-fileupload' ;
3+ import { v4 as uuidv4 } from 'uuid' ;
4+ import path from 'path' ;
5+ import fs from 'fs' ;
6+ //user fs-extra en caso quieras usar await
7+ import { Product } from "../models" ;
8+
9+ class ProductController {
10+
11+ constructor ( ) {
12+
13+ }
14+
15+ async get ( req : Request , res : Response ) {
16+ try {
17+ const { idProduct } = req . params ;
18+ const product = await Product . findById ( idProduct ) ;
19+ return res . status ( 200 ) . json ( {
20+ ok : true ,
21+ product
22+ } ) ;
23+ } catch ( err ) {
24+ return res . status ( 500 ) . json ( {
25+ ok : false ,
26+ err
27+ } ) ;
28+ }
29+ }
30+
31+ async getAll ( req : Request , res : Response ) {
32+ try {
33+ const products = await Product . find ( { } ) . sort ( { name : 1 } ) ;
34+ return res . status ( 200 ) . json ( {
35+ ok : true ,
36+ products
37+ } ) ;
38+ } catch ( err ) {
39+ return res . status ( 500 ) . json ( {
40+ ok : false ,
41+ err
42+ } ) ;
43+ }
44+ }
45+
46+ async post ( req : Request , res : Response ) {
47+ try {
48+ const { name, price, category, quantity } = req . body ;
49+ const photo = < UploadedFile > req . files ?. photo ;
50+ const namePhoto = `${ uuidv4 ( ) . toLowerCase ( ) } ${ path . extname ( photo . name ) } ` ;
51+ const newProduct = new Product ( { name, price, category, quantity, photo : namePhoto } ) ;
52+ const product = await newProduct . save ( ) ;
53+ await photo . mv ( `src/uploads/products/${ namePhoto } ` ) ;
54+ return res . status ( 201 ) . json ( {
55+ ok : true ,
56+ product
57+ } ) ;
58+
59+ } catch ( err ) {
60+ return res . status ( 500 ) . json ( {
61+ ok : false ,
62+ err
63+ } ) ;
64+ }
65+ }
66+
67+ async getImage ( req : Request , res : Response ) {
68+ try {
69+ const { img } = req . params ;
70+ const route = path . join ( __dirname , './../uploads/products/' , img ) ;
71+ if ( ! fs . existsSync ( route ) ) {
72+ return res . sendFile ( path . join ( __dirname , './../uploads/products/' , 'no-photo.png' ) ) ;
73+ }
74+ return res . sendFile ( route ) ;
75+ } catch ( err ) {
76+ return res . status ( 500 ) . json ( {
77+ ok : false ,
78+ err
79+ } ) ;
80+ }
81+ }
82+
83+ }
84+
85+ export default ProductController
0 commit comments