1
1
import { INestApplication } from '@nestjs/common' ;
2
- import { DocumentBuilder , SwaggerModule } from '@nestjs/swagger' ;
2
+ import { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface' ;
3
+ import { ApiBody , DocumentBuilder , SwaggerModule } from '@nestjs/swagger' ;
4
+ import { diskStorage } from 'multer' ;
5
+ import { extname } from 'path' ;
3
6
4
7
export const swaggerSetup = ( app : INestApplication ) => {
5
8
const documentBuilder = new DocumentBuilder ( )
@@ -12,3 +15,59 @@ export const swaggerSetup = (app: INestApplication) => {
12
15
const document = SwaggerModule . createDocument ( app , documentBuilder ) ;
13
16
SwaggerModule . setup ( 'api/docs' , app , document ) ;
14
17
} ;
18
+
19
+ export const ApiFile = ( fileName : string = 'file' ) : MethodDecorator => (
20
+ target : any ,
21
+ propertyKey : string ,
22
+ descriptor : PropertyDescriptor ,
23
+ ) => {
24
+ ApiBody ( {
25
+ schema : {
26
+ type : 'object' ,
27
+ properties : {
28
+ [ fileName ] : {
29
+ type : 'string' ,
30
+ format : 'binary' ,
31
+ } ,
32
+ } ,
33
+ } ,
34
+ } ) ( target , propertyKey , descriptor ) ;
35
+ } ;
36
+
37
+ export const ApiFiles = ( fileName : string = 'files' ) : MethodDecorator => (
38
+ target : any ,
39
+ propertyKey : string ,
40
+ descriptor : PropertyDescriptor ,
41
+ ) => {
42
+ ApiBody ( {
43
+ type : 'multipart/form-data' ,
44
+ required : true ,
45
+ schema : {
46
+ type : 'object' ,
47
+ properties : {
48
+ [ fileName ] : {
49
+ type : 'array' ,
50
+ items : {
51
+ type : 'string' ,
52
+ format : 'binary' ,
53
+ } ,
54
+ } ,
55
+ } ,
56
+ } ,
57
+ } ) ( target , propertyKey , descriptor ) ;
58
+ } ;
59
+
60
+ export const MulterConfig : MulterOptions = {
61
+ storage : diskStorage ( {
62
+ destination : './uploads' ,
63
+ filename : ( req , file , cb ) => {
64
+ // Generating a 32 random chars long string
65
+ const randomName = Array ( 32 )
66
+ . fill ( null )
67
+ . map ( ( ) => Math . round ( Math . random ( ) * 16 ) . toString ( 16 ) )
68
+ . join ( '' ) ;
69
+ //Calling the callback passing the random name generated with the original extension name
70
+ cb ( null , `${ randomName } ${ extname ( file . originalname ) } ` ) ;
71
+ } ,
72
+ } ) ,
73
+ } ;
0 commit comments