From 2c958dae08fecd80c611d87559ae6253a95e7186 Mon Sep 17 00:00:00 2001 From: Vipul Gupta <55375170+vipul0425@users.noreply.github.com> Date: Mon, 16 Dec 2024 12:06:01 +0530 Subject: [PATCH] Integrate Nutritionix API to automatically fill calories Related to #4 Testing the copilot workspace. --- For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/vipul0425/Calorie-Tracker/issues/4?shareId=XXXX-XXXX-XXXX-XXXX). --- app.js | 30 ++++++++++++++++++++++++------ index.html | 4 ++-- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/app.js b/app.js index c70eb6a..6fecc22 100644 --- a/app.js +++ b/app.js @@ -1,5 +1,3 @@ -// storage Controller - const StorageCtrl = function(){ return { storeItem: function(item){ @@ -286,13 +284,14 @@ const AppCtrl = function (ItemCtrl, StorageCtrl, UICtrl) { } // Add Items Function - function addItems(e) { + async function addItems(e) { const meal = document.querySelector(UICtrl.getUiSelectors().mealInput); const calories = document.querySelector(UICtrl.getUiSelectors().caloriesInput); // ADD ITEMS - if (meal.value !== '' && calories.value !== '') { - const newItem = ItemCtrl.addMeal(meal.value, calories.value); + if (meal.value !== '') { + const fetchedCalories = await fetchCalories(meal.value); + const newItem = ItemCtrl.addMeal(meal.value, fetchedCalories); // add this item into ui UICtrl.addListItem(newItem); @@ -310,6 +309,25 @@ const AppCtrl = function (ItemCtrl, StorageCtrl, UICtrl) { e.preventDefault(); } + // Fetch Calories Function + async function fetchCalories(meal) { + const apiKey = 'YOUR_API_KEY'; + const apiId = 'YOUR_API_ID'; + const response = await fetch(`https://trackapi.nutritionix.com/v2/natural/nutrients`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-app-id': apiId, + 'x-app-key': apiKey + }, + body: JSON.stringify({ + query: meal + }) + }); + const data = await response.json(); + return data.foods[0].nf_calories; + } + //Enable Edit State const enableEditState = function(e){ @@ -408,4 +426,4 @@ const AppCtrl = function (ItemCtrl, StorageCtrl, UICtrl) { }(ItemCtrl,StorageCtrl, UICtrl) -AppCtrl.init(); \ No newline at end of file +AppCtrl.init(); diff --git a/index.html b/index.html index 04e9fea..d118c6d 100644 --- a/index.html +++ b/index.html @@ -89,7 +89,7 @@
- +
@@ -130,4 +130,4 @@
Total Calories : 0
- \ No newline at end of file +