forked from fullstackreact/food-lookup-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
68 lines (58 loc) · 1.69 KB
/
server.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
const express = require("express");
const fs = require("fs");
const sqlite = require("sql.js");
const filebuffer = fs.readFileSync("db/usda-nnd.sqlite3");
// comented below line as it stopped working, follow the next lines to create db
// const db = new sqlite.Database(filebuffer);
let db;
sqlite().then((SQL) => {
// Create a database
db = new SQL.Database(filebuffer);
});
const app = express();
app.set("port", process.env.PORT || 3001);
// Express only serves static assets in production
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
const COLUMNS = ["carbohydrate_g", "protein_g", "fa_sat_g", "fa_mono_g", "fa_poly_g", "kcal", "description"];
app.get("/api/food", (req, res) => {
const param = req.query.q;
if (!param) {
res.json({
error: "Missing required parameter `q`"
});
return;
}
// WARNING: Not for production use! The following statement
// is not protected against SQL injections.
const r = db.exec(
`
select ${COLUMNS.join(", ")} from entries
where description like '%${param}%'
limit 20
`
);
if (r[0]) {
res.json(
r[0].values.map((entry) => {
const e = {};
COLUMNS.forEach((c, idx) => {
// combine fat columns
if (c.match(/^fa_/)) {
e.fat_g = e.fat_g || 0.0;
e.fat_g = (parseFloat(e.fat_g, 10) + parseFloat(entry[idx], 10)).toFixed(2);
} else {
e[c] = entry[idx];
}
});
return e;
})
);
} else {
res.json([]);
}
});
app.listen(app.get("port"), () => {
console.log(`Find the server at: http://localhost:${app.get("port")}/`); // eslint-disable-line no-console
});