@@ -47,60 +47,68 @@ const addHistory = async (req, res) => {
47
47
} ) ;
48
48
}
49
49
50
- const { artist, art } = req . body ;
50
+ const theme = await Theme . findOne ( { slug } ) ;
51
+ if ( ! theme ) {
52
+ return res . status ( 404 ) . json ( {
53
+ status : "error" ,
54
+ message : "Theme not found." ,
55
+ } ) ;
56
+ }
51
57
58
+ const { artist, art } = req . body ;
52
59
if ( ! artist || ! art ) {
53
- return res . status ( 404 ) . json ( {
60
+ return res . status ( 400 ) . json ( {
54
61
status : "error" ,
55
62
message : "artist and art is required" ,
56
63
} ) ;
57
64
}
58
65
59
66
let image = "" ;
60
-
67
+ let newFilename = "" ;
61
68
if ( req . file ) {
69
+ const historyCount = theme . history . length + 1 ;
70
+ console . log ( historyCount ) ;
62
71
let oldFilename = req . file . filename ;
63
- let extension = oldFilename . split ( "." ) [ oldFilename . split ( "." ) . length - 1 ] ;
64
- image = slug + "." + extension ;
65
-
72
+ let extension = oldFilename . split ( "." ) . pop ( ) ;
73
+ newFilename = ` ${ slug } -h- ${ historyCount } . ${ extension } ` ;
74
+
66
75
fs . rename (
67
76
req . file . path ,
68
- req . file . destination + "/" + image ,
77
+ req . file . destination + "/" + newFilename ,
69
78
function ( err ) {
70
79
if ( err ) {
71
80
throw new Error ( "Error renaming file. Error: " + err ) ;
72
81
}
73
- } ) ;
74
- image = "/theme/" + image ;
75
-
82
+ }
83
+ ) ;
84
+ image = "/theme/" + newFilename ;
76
85
} else {
77
86
return res . status ( 400 ) . json ( {
78
87
status : "error" ,
79
88
message : "Image is required"
80
89
} ) ;
81
90
}
82
-
83
- const theme = await Theme . findOne ( { slug } ) ;
84
- if ( ! theme ) {
85
- return res . status ( 404 ) . json ( {
86
- status : "error" ,
87
- message : "Theme not found." ,
88
- } ) ;
89
- }
90
-
91
+ console . log ( image ) ;
91
92
const historyEntry = {
92
93
src : image ,
93
94
artist : JSON . parse ( artist ) ,
94
- art : JSON . parse ( art ) ,
95
+ art : JSON . parse ( art )
95
96
} ;
96
- console . log ( historyEntry ) ;
97
97
98
98
theme . history . push ( historyEntry ) ;
99
99
await theme . save ( ) ;
100
100
101
- return res . status ( 201 ) . json ( theme ) ;
101
+ return res . status ( 200 ) . json ( {
102
+ status : "success" ,
103
+ message : "History added successfully" ,
104
+ theme,
105
+ filename : newFilename
106
+ } ) ;
102
107
} catch ( e ) {
103
- console . log ( e )
108
+ console . log ( e ) ;
109
+ if ( req . file ) {
110
+ fs . existsSync ( req . file . path ) && deleteFile ( req . file . path ) ;
111
+ }
104
112
return res . status ( 500 ) . json ( {
105
113
status : "error" ,
106
114
message : "Something went wrong." ,
0 commit comments