forked from hack4impact-calpoly/bootcamp-grocery-prep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsurpriseMe.js
80 lines (64 loc) · 2.09 KB
/
surpriseMe.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
const recipeHash = window.location.hash.substring(1)
const getParam = recipeHash !== undefined ? '?id=' + recipeHash : null
const URL = 'https://3blzgwgi13.execute-api.us-west-2.amazonaws.com/Live/recipe'
let alldata;
const getRecipe = () => {
fetch(URL + getParam)
.then(response => response.json())
.then(data => parseData(data))
document.addEventListener('click', event => {
if (event.target.id === 'post-rating')
postRating()
})
}
const parseData = (data) => {
alldata = data;
document.location.hash = data._id
document.getElementById('title').innerText = data.title;
document.getElementById('desc').innerText = data.desc;
document.getElementById('picture').src = data.picture;
document.getElementById('count').innerText = data.servings;
document.getElementById('rating').innerText = data.rating;
const ingredients = document.getElementById('ingredients')
for (const [key, value] of Object.entries(data.ingredients)) {
const item = document.createElement('li')
const count = document.createElement('span')
count.className = 'amount'
count.innerText = value
item.appendChild(count)
item.innerHTML += " " + key
ingredients.appendChild(item)
}
data.instructions.forEach(instruction => {
const item = document.createElement('li')
item.innerText = instruction
document.getElementById('instructions').appendChild(item)
})
document.getElementById('rating').innerText = avgRatings(data.ratings)
}
const postRating = () => {
const ratingSelect = document.getElementById('select-rating')
const rating = +(ratingSelect.options[ratingSelect.selectedIndex].value)
const data = {
id: alldata._id,
rating: rating
}
fetch(URL, {
method: 'POST',
body: JSON.stringify(data)
})
.then(() => {
alldata.ratings.push(rating)
document.getElementById('rating').innerText = avgRatings(alldata.ratings)
})
.catch((err) => {
console.error(err)
})
}
const avgRatings = (ratings) => {
let sum = 0
for (const i in ratings)
sum += +(ratings[i])
return (sum / ratings.length).toFixed(1)
}
getRecipe()