class 3-5 initial
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
class meal_list extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
const now = new Date();
|
||||
const hours = now.getHours();
|
||||
|
||||
this.date = new Date()
|
||||
.toISOString()
|
||||
.slice(0, 10)
|
||||
.replace(/-/g, "");
|
||||
|
||||
switch (true) {
|
||||
case hours < 8:
|
||||
this.selectedType = 1;
|
||||
break;
|
||||
case hours < 14:
|
||||
this.selectedType = 2;
|
||||
break;
|
||||
default:
|
||||
this.selectedType = 3;
|
||||
}
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
this.render();
|
||||
}
|
||||
|
||||
async get_meal(date, type) {
|
||||
try {
|
||||
console.log(`/api/meal?date=${date}&type=${type}`)
|
||||
let response = await fetch(`/api/meal?date=${date}&type=${type}`);
|
||||
|
||||
if (!response.ok) throw new Error("Failed to fetch meal data");
|
||||
|
||||
let data = await response.json();
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error("❌ API Error:", error);
|
||||
return ["식단 정보를 불러올 수 없습니다."];
|
||||
}
|
||||
}
|
||||
|
||||
async render() {
|
||||
const header = document.createElement("header");
|
||||
|
||||
const select = document.createElement("select");
|
||||
const types = ["아침", "점심", "저녁"];
|
||||
types.forEach((type, index) => {
|
||||
const option = document.createElement("option");
|
||||
option.textContent = types[index];
|
||||
option.value = index + 1;
|
||||
if (index + 1 === this.selectedType) option.selected = true;
|
||||
select.appendChild(option);
|
||||
});
|
||||
select.addEventListener("change", async () => {
|
||||
this.selectedType = Number(select.value);
|
||||
await this.render();
|
||||
});
|
||||
|
||||
const res = await this.get_meal(this.date, this.selectedType);
|
||||
|
||||
const ul = document.createElement("ul");
|
||||
res.meal_list.forEach((meal) => {
|
||||
const li = document.createElement("li");
|
||||
li.textContent = meal;
|
||||
ul.appendChild(li);
|
||||
});
|
||||
|
||||
const kcal = document.createElement("p");
|
||||
kcal.textContent = res.kcal;
|
||||
|
||||
header.appendChild(select);
|
||||
header.appendChild(kcal);
|
||||
|
||||
this.innerHTML = "";
|
||||
this.append(header);
|
||||
this.appendChild(ul);
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define("meal-list", meal_list);
|
||||
Reference in New Issue
Block a user