-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (71 loc) · 1.99 KB
/
index.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
var fs = require("fs");
var data = fs.readFileSync("data.json", "utf8");
var foods = JSON.parse(data);
function guidGenerator() {
return Date.now().toString(36) + Math.random().toString(36).substr(2);
}
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const port = process.env.PORT || 3030;
app.use(cors());
// Configuring body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Home Route - List All Foods
app.get("/", (req, res) => {
res.send(foods);
});
//Pass Random - Get random Food
app.get("/random", (req, res) => {
let response = [];
response = [...response, foods[Math.floor(Math.random() * foods.length)]];
res.send(response);
return;
});
//Pass Query to food_description
app.get("/s/:term", (req, res) => {
let response = [];
const term = req.params.term;
// Searching books for the term
for (let food of foods) {
if (food.food_description.includes(term.toLocaleUpperCase())) {
response = [...response, food];
}
}
if (response.length !== 0) {
res.json(response);
return;
} else {
res.status(404).send({
error: "No Results Found",
errorMessage: "Could not find any foods that match this query; " + term,
});
return;
}
// Sending 404 when not found something is a good practice
});
//Pass food_description as Query
app.get("/f/:id", (req, res) => {
let response = [];
const id = req.params.id;
// Searching books for the id
for (let food of foods) {
if (food.id == id.toLocaleLowerCase()) {
response = [...response, food];
}
}
if (response.length !== 0) {
res.json(response);
return;
} else {
res.status(404).send({
error: "No Results Found",
errorMessage: "Could not find any foods with this ID; " + id,
});
return;
}
// Sending 404 when not found something is a good practice
});
app.listen(port, () => console.log(`Listening on port ${port}!`));