-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
97 lines (89 loc) · 2.4 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const express = require('express');
const http = require('http');
const concat = require('concat-stream');
const APP_ID = process.env.APP_ID
const PORT = process.env.PORT || 8889;
const BASE = '/v1_1/search/';
const FIELDS = [
'item_name',
'item_id',
'brand_name',
'nf_calories',
'nf_total_fat',
'nf_protein',
'nf_total_carbohydrate',
'nf_serving_size_qty',
'nf_serving_size_unit',
'nf_serving_weight_grams'
];
const app = express();
const buildQuery = (query, fields) => (encodeURI(`${query}?fields=${fields.join(',')}`));
const getPath = (query, base, fields, appId) => (
base + buildQuery(query.trim(), fields) + `&appId=${appId}`
);
const indexHandler = (req, res) => {
const {
query: {
text
}
} = req;
if (!text) return res.sendStatus(400);
http.get({
host: 'api.nutritionix.com',
path: getPath(text, BASE, FIELDS, APP_ID),
}, (getRes) => {
getRes.on('error', (err) => {
console.log(error);
})
getRes.pipe(concat((buf) => {
var hits = JSON.parse(buf.toString()).hits;
if (!hits.length) {
return res.json({
"response_type": "ephemeral",
"text": 'Couldn\'t find whatever weird thing you search for.',
});
}
var data = hits[0].fields;
return res.json({
"response_type": "in_channel",
"text": `${data.item_name} - ${data.brand_name}`,
"attachments": [
{
"fields": [
{
"title": "Serving size",
"value": `${data.nf_serving_size_qty}${data.nf_serving_size_unit} / ${data.nf_serving_weight_grams}g`,
"short": false
},
{
"title": "Calories",
"value": data.nf_calories,
"short": true
},
{
"title": "Protein (g)",
"value": data.nf_protein,
"short": true
},
{
"title": "Carbs (g)",
"value": data.nf_total_carbohydrate,
"short": true
},
{
"title": "Fat (g)",
"value": data.nf_total_fat,
"short": true
}
],
"color": "#ffcc66"
}
]
});
}));
});
}
app.use('/', indexHander);
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});