forked from foodTrackingApplication/scratchProject
-
Notifications
You must be signed in to change notification settings - Fork 0
/
getFoodMiddleware.js
89 lines (73 loc) · 2.72 KB
/
getFoodMiddleware.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
const path = require('path');
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
const foodController = {};
foodController.getProduct = async (req, res, next) => {
const searchTerm = req.body.searchTerm;
const url = `https://world.openfoodfacts.org/cgi/search.pl?search_terms=${searchTerm}&search_simple=1&action=process&json=1`;
try {
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
// UserAgent: userAgent
}
});
const product = await response.json();
// console.log('this is the products page', product)
// res.locals.searchResults = product;
// const { energy-kcal_100g, sodium_100g, fat_100g, saturated - fat_100g, fiber_100g, proteins_100g, sugars_100g
// } = product.product[0].nutriments;
let i = 0;
let resultsArray = [];
while (i < 5) {
// foodArray = Object.keys(foodObj);
// for (let item in foodArray) {
// res.locals.product[i][item] = foodObj[item]
const {
sodium_100g,
fat_100g,
fiber_100g,
proteins_100g,
sugars_100g
} = product.products[i].nutriments;
const energy_kcal_100g = product.products[i].nutriments['energy-kcal_100g'];
const saturated_fat_100g = product.products[i].nutriments['saturated-fat_100g'];
const calAndFatObj = { energy_kcal_100g: energy_kcal_100g, saturated_fat_100g: saturated_fat_100g}
const { product_name } = product.products[i].product_name;
const { image_url } = product.products[i].image_url;
const foodObj = Object.assign({
...calAndFatObj,
sodium_100g,
fat_100g,
fiber_100g,
proteins_100g,
sugars_100g
}, {energy_kcal_100g}, { saturated_fat_100g }, { product_name }, { image_url });
// const {kcal, energy-kcal_100g} = product.product[i].nutriments
resultsArray.push(foodObj);
i++
};
res.locals.searchResults = resultsArray;
console.log(resultsArray);
// console.log('This is the res.locals', res.locals.searchResults)
// if (product.status === 0) {
// return null;
// }
return next();
} catch (error) {
console.error(error);
return null;
}
}
module.exports = foodController;
/*
"energy-kcal_100g": 180,
"sodium_100g": 0.16,
"carbohydrates_100g": 26.9,
"fat_100g": 7,
"saturated-fat_100g": 0.8,
"fiber_100g": 2.3,
"proteins_100g": 2.3,
"sugars_100g": 0.2,
*/