@@ -20,6 +20,94 @@ const index = async (req, res) => {
20
20
}
21
21
} ;
22
22
23
+ const themeOfDay = async ( req , res ) => {
24
+ try {
25
+ const themes = await Theme . find ( ) ;
26
+ const idx = new Date ( ) . getDate ( ) % themes . length ;
27
+
28
+ return res . status ( 200 ) . json ( {
29
+ status : "success" ,
30
+ theme : themes [ idx ] ,
31
+ } ) ;
32
+ } catch ( e ) {
33
+ return res . status ( 500 ) . json ( {
34
+ status : "error" ,
35
+ message : "Something went wrong." ,
36
+ } ) ;
37
+ }
38
+ }
39
+
40
+ const addHistory = async ( req , res ) => {
41
+ try {
42
+ const slug = req . params . slug ;
43
+ if ( ! slug ) {
44
+ return res . status ( 400 ) . json ( {
45
+ status : "error" ,
46
+ message : "Slug is required" ,
47
+ } ) ;
48
+ }
49
+
50
+ const { artist, art } = req . body ;
51
+
52
+ if ( ! artist || ! art ) {
53
+ return res . status ( 404 ) . json ( {
54
+ status : "error" ,
55
+ message : "artist and art is required" ,
56
+ } ) ;
57
+ }
58
+
59
+ let image = "" ;
60
+
61
+ if ( req . file ) {
62
+ let oldFilename = req . file . filename ;
63
+ let extension = oldFilename . split ( "." ) [ oldFilename . split ( "." ) . length - 1 ] ;
64
+ image = slug + "." + extension ;
65
+
66
+ fs . rename (
67
+ req . file . path ,
68
+ req . file . destination + "/" + image ,
69
+ function ( err ) {
70
+ if ( err ) {
71
+ throw new Error ( "Error renaming file. Error: " + err ) ;
72
+ }
73
+ } ) ;
74
+ image = "/images/theme/" + image ;
75
+
76
+ } else {
77
+ return res . status ( 400 ) . json ( {
78
+ status : "error" ,
79
+ message : "Image is required"
80
+ } ) ;
81
+ }
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
+ const historyEntry = {
92
+ src : image ,
93
+ artist : JSON . parse ( artist ) ,
94
+ art : JSON . parse ( art ) ,
95
+ } ;
96
+ console . log ( historyEntry ) ;
97
+
98
+ theme . history . push ( historyEntry ) ;
99
+ await theme . save ( ) ;
100
+
101
+ return res . status ( 201 ) . json ( theme ) ;
102
+ } catch ( e ) {
103
+ console . log ( e )
104
+ return res . status ( 500 ) . json ( {
105
+ status : "error" ,
106
+ message : "Something went wrong." ,
107
+ } ) ;
108
+ }
109
+ }
110
+
23
111
const show = async ( req , res ) => {
24
112
try {
25
113
const slug = req . params . slug ;
@@ -244,4 +332,4 @@ const destroy = async (req, res) => {
244
332
} ;
245
333
// TODO: Select a random theme for theme of the day
246
334
247
- module . exports = { index, show, create, edit, destroy } ;
335
+ module . exports = { index, show, create, edit, destroy, themeOfDay , addHistory } ;
0 commit comments