-
Notifications
You must be signed in to change notification settings - Fork 13
/
server.js
73 lines (63 loc) · 1.68 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
69
70
71
72
73
const express = require('express');
const fs = require('fs');
const initSqlJs = require('sql.js');
initSqlJs().then((sqlite) => {
const filebuffer = fs.readFileSync('db/usda-nnd.sqlite3');
const db = new sqlite.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 100
`,
);
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
});
});