@@ -6,7 +6,12 @@ import {
66 Put ,
77 Param ,
88 Delete ,
9+ UseInterceptors ,
10+ UploadedFiles ,
911} from '@nestjs/common' ;
12+ import { FilesInterceptor } from '@nestjs/platform-express' ;
13+ import { diskStorage } from 'multer' ;
14+ import { extname } from 'path' ;
1015import { GalleryService } from '../application/gallery.service' ;
1116import { Gallery } from '../domain/gallery.entity' ;
1217import { CreateGalleryDto } from './dto/create-gallery.dto' ;
@@ -27,23 +32,73 @@ export class GalleryController {
2732 }
2833
2934 @Post ( )
30- async create ( @Body ( ) createGalleryDto : CreateGalleryDto ) : Promise < Gallery > {
35+ @UseInterceptors (
36+ FilesInterceptor ( 'files' , 10 , {
37+ storage : diskStorage ( {
38+ destination : './uploads/gallery' ,
39+ filename : ( req , file , callback ) => {
40+ const uniqueSuffix =
41+ Date . now ( ) + '-' + Math . round ( Math . random ( ) * 1e9 ) ;
42+ const ext = extname ( file . originalname ) ;
43+ callback ( null , `${ file . fieldname } -${ uniqueSuffix } ${ ext } ` ) ;
44+ } ,
45+ } ) ,
46+ } ) ,
47+ )
48+ async create (
49+ @Body ( ) createGalleryDto : CreateGalleryDto ,
50+ @UploadedFiles ( ) files : Array < Express . Multer . File > ,
51+ ) : Promise < Gallery > {
52+ const imagePath =
53+ files && files . length > 0
54+ ? `/uploads/gallery/${ files [ 0 ] . filename } `
55+ : null ;
56+
57+ const galleryData = {
58+ ...createGalleryDto ,
59+ imageUrl : imagePath || ( createGalleryDto as any ) . imageUrl ,
60+ } ;
61+
3162 // Mapping DTO to Domain Entity
32- const gallery = createGalleryDto as unknown as Omit <
33- Gallery ,
34- 'id' | 'createdAt'
35- > ;
63+ const gallery = galleryData as unknown as Omit < Gallery , 'id' | 'createdAt' > ;
3664 return this . galleryService . create ( gallery ) ;
3765 }
3866
3967 @Put ( ':id' )
68+ @UseInterceptors (
69+ FilesInterceptor ( 'files' , 10 , {
70+ storage : diskStorage ( {
71+ destination : './uploads/gallery' ,
72+ filename : ( req , file , callback ) => {
73+ const uniqueSuffix =
74+ Date . now ( ) + '-' + Math . round ( Math . random ( ) * 1e9 ) ;
75+ const ext = extname ( file . originalname ) ;
76+ callback ( null , `${ file . fieldname } -${ uniqueSuffix } ${ ext } ` ) ;
77+ } ,
78+ } ) ,
79+ } ) ,
80+ )
4081 async update (
4182 @Param ( 'id' ) id : string ,
4283 @Body ( ) updateGalleryDto : UpdateGalleryDto ,
84+ @UploadedFiles ( ) files : Array < Express . Multer . File > ,
4385 ) : Promise < Gallery > {
86+ const imagePath =
87+ files && files . length > 0
88+ ? `/uploads/gallery/${ files [ 0 ] . filename } `
89+ : null ;
90+
91+ const galleryData = {
92+ ...updateGalleryDto ,
93+ } ;
94+
95+ if ( imagePath ) {
96+ ( galleryData as any ) . imageUrl = imagePath ;
97+ }
98+
4499 return this . galleryService . update (
45100 id ,
46- updateGalleryDto as unknown as Partial < Gallery > ,
101+ galleryData as unknown as Partial < Gallery > ,
47102 ) ;
48103 }
49104
0 commit comments