-
Notifications
You must be signed in to change notification settings - Fork 16
/
app.js
206 lines (184 loc) · 6.79 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
const express = require('express');
const fs = require('fs');
const cors = require('cors');
const swaggerUI = require('swagger-ui-express');
const swaggerJSON = require('./docs/swagger-api.json');
const PORT = process.env.PORT || 3000;
const app = express();
app.use(cors());
app.use('/images', express.static(`${__dirname}/public/assets/images`));
app.use('/assets', express.static(`${__dirname}/public`));
app.set('view engine', 'ejs');
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerJSON));
const MENU_DB = ['biryani', 'burger', 'butter-chicken', 'dessert', 'dosa', 'idly', 'pasta', 'pizza', 'rice', 'samosa'];
const getImageCount = () => {
const imageMetaData = [];
const imageMetaDataFetch = fs.readFileSync('./scripts/deployment/imageMetaData.json', 'utf-8');
const imageMetaDataJSON = JSON.parse(imageMetaDataFetch);
for (const obj in imageMetaDataJSON) {
if (obj === 'total') {
imageMetaData.push({
title: 'Total Foodishes',
count: imageMetaDataJSON[obj]
});
} else {
imageMetaData.push({
title: obj,
count: imageMetaDataJSON[obj]
});
}
}
return imageMetaData;
};
// UI CALLS
app.get('/', (req, res) => {
// #swagger.ignore = true
// random number generator within MENU_DB array range
const randomSelector = Math.floor(Math.random() * MENU_DB.length);
// anyRandomFood is burger
const anyRandomFood = MENU_DB[randomSelector];
// random number generator within all burger model images
// randomFoodDB is the array of objects from the json model
const randomFoodModel = JSON.parse(fs.readFileSync(`./models/${anyRandomFood}.json`, 'utf8'));
const randomFoodDB = randomFoodModel[anyRandomFood];
// catchOfTheDay is the object with image burger101.jpg
const randomFood = Math.floor(Math.random() * randomFoodDB.length);
const catchOfTheDay = randomFoodDB[randomFood];
res.render('foodish', {
food: {
image: `${anyRandomFood}/${catchOfTheDay.image}`,
foodDB: getImageCount()
}
});
});
app.get('/images/:food', (req, res) => {
// #swagger.ignore = true
// food is pizza
const { food } = req.params;
let finalFood;
// (optional) keyword is margherita
const keyword = req.query.keyword ? req.query.keyword : '';
// foodPath points to pizza model
const foodPath = `./models/${food}.json`;
// check if pizza model exists
if (fs.existsSync(foodPath)) {
// get all pizza images from pizza model
const foodModel = JSON.parse(fs.readFileSync(foodPath, 'utf8'));
const foodDB = foodModel[food];
// check if keyword requested
if (keyword) {
// filter pizza images matching with keyword margherita
let filteredFood = [];
foodDB.forEach((eachFood) => {
eachFood.keywords.forEach((key) => {
if (key.toLowerCase() === keyword.toLowerCase()) {
filteredFood.push(eachFood);
}
});
});
// randomly select one pizza image if none matched
if (filteredFood.length === 0) {
const randomFood = Math.floor(Math.random() * foodDB.length);
finalFood = foodDB[randomFood];
} else {
// randomly select one pizza image from filteredFood
const randomFood = Math.floor(Math.random() * filteredFood.length);
finalFood = filteredFood[randomFood];
}
} else {
// randomly select one pizza image
const randomFood = Math.floor(Math.random() * foodDB.length);
finalFood = foodDB[randomFood];
}
res.render('foodish', { food: { image: `${food}/${finalFood.image}` } });
} else {
res.render('notfound', { food: { foodDB: getImageCount() } });
}
});
// API CALLS
app.get('/api', (req, res) => {
// #swagger.tags = ['API']
// #swagger.description = 'Get a random food dish image.'
/* #swagger.responses[200] = {
description: "OK",
content: {
"application/json": {
example:{
image: "https://foodish-api.com/images/burger/burger101.jpg"
}
}
}
}
*/
try {
const randomSelector = Math.floor(Math.random() * MENU_DB.length);
const anyRandomFood = MENU_DB[randomSelector];
const randomFoodModel = JSON.parse(fs.readFileSync(`./models/${anyRandomFood}.json`, 'utf8'));
const randomFoodDB = randomFoodModel[anyRandomFood];
const randomFood = Math.floor(Math.random() * randomFoodDB.length);
const catchOfTheDay = randomFoodDB[randomFood];
res.status(200).send({
image: `https://foodish-api.com/images/${anyRandomFood}/${catchOfTheDay.image}`
});
} catch (error) {
res.status(500).send({ error });
}
});
app.get('/api/images/:food', (req, res) => {
// #swagger.tags = ['API']
// #swagger.description = 'Get a random food dish image from "food" category.'
// #swagger.parameters['food'] = { description: 'Required food category.' }
// #swagger.parameters['keyword'] = { description: 'Optional filter for food category image. (Beta version: only works for pizza food category. More details: https://github.com/surhud004/Foodish/discussions/14).' }
/* #swagger.responses[200] = {
description: "OK",
content: {
"application/json": {
example:{
image: "https://foodish-api.com/images/burger/burger101.jpg"
}
}
}
}
*/
try {
const { food } = req.params;
let finalFood;
const keyword = req.query.keyword ? req.query.keyword : '';
const foodPath = `./models/${food}.json`;
if (fs.existsSync(foodPath)) {
const foodModel = JSON.parse(fs.readFileSync(foodPath, 'utf8'));
const foodDB = foodModel[food];
if (keyword) {
let filteredFood = [];
foodDB.forEach((eachFood) => {
eachFood.keywords.forEach((key) => {
if (key.toLowerCase() === keyword.toLowerCase()) {
filteredFood.push(eachFood);
}
});
});
if (filteredFood.length === 0) {
const randomFood = Math.floor(Math.random() * foodDB.length);
finalFood = foodDB[randomFood];
} else {
const randomFood = Math.floor(Math.random() * filteredFood.length);
finalFood = filteredFood[randomFood];
}
} else {
const randomFood = Math.floor(Math.random() * foodDB.length);
finalFood = foodDB[randomFood];
}
res.status(200).send({ image: `https://foodish-api.com/images/${food}/${finalFood.image}` });
} else {
res.status(404).send({ error: 'Not found.' });
}
} catch (error) {
res.status(500).send({ error });
}
});
app.get('*', (req, res) => {
res.status(404).send({ error: 'Not found.' });
});
app.listen(PORT, () => {
console.log(`Server running on ${PORT}`);
});