My footsteps

RestController / 5 본문

국비수업/수업정리

RestController / 5

밀김 2023. 6. 21. 15:10
728x90

 

 

 

 

 

 

 

 

 

 

단위가 모두 레코드(객체) 단위

 

 

 

- 페이지는 뷰를 쓰는게 아니다

 

 

- 구조/조직/자원 등의 디렉토리 구조를 범용화 한 것

ex)삼성전자/개발팀/프론트/사원/1 이런것처럼

 

 

- restpullapi는 자원에 대한 식별자를 붙이는거다(?) 

 

 

- 뷰 : 모든 필요한 집계 데이터를 꾸겨 넣는다

 

 

-json : 객체를 객체스럽지 않게 표현식으로 제공하는것(한방에 쌉가능)

.then(response=>response.json())

 

 

 

 

 

- count 하는법

.then(result => {
        if(result==1){
            fetch(`/api/menulikes/count?mn=${menuId}`)
            .then(response=>response.json())
            .then(count=>{
                console.log(`count is ${count}`);
            });
        }

    });

 

 

 

 

- 좋아요 카운트 텍스트 업데이트

fetch(`/api/menulikes/count?mn=${menuId}`)
    .then(response => response.text())
    .then(value => parseInt(value))
    .then(count => {
        el.nextElementSibling.innerText = count; // HTML에서 좋아요 수를 업데이트합니다.
        console.log(`count is ${count}`);
    });

 

 

 

 

 

 

 

- 전체적인 흐름....

function menuListLoad(url) {
	let menuList = document.querySelector(".menu-list");
	fetch(url)
		.then(response => response.json())
		.then(list => {
			console.log(list);

			//비우기
			menuList.innerHTML = "";

			//채우기
			for (let menu of list) {
				let itemTemplate = `<section class="menu" >

                  <div>
                     <a href="detail">
                        <img src="/image/${menu.img}" alt="에스프레소" />
                     </a>
                  </div>
                  <h1>${menu.korName}</h1>
                  <h2>${menu.engName}</h2>
                  <div>${menu.price}</div>
                  <div>
                     <a href="detail?id=${menu.id}" class="icon icon-heart" ${menu.like ? 'icon-heart-fill' : ''}" ></a>
                        <span th:text ="${menu.likeCount}">0</span>
                  </div>
                  <div>
                     <a href="#" class="icon icon-plus icon-lg">추가</a>
                     <a href="#" class="icon icon-cart icon-lg">장바구니</a>
                  </div>
               </section>`;
				menuList.insertAdjacentHTML("beforeend", itemTemplate);
			};
		});
}

window.addEventListener("load", function(e) {

	let menuListSection = document.querySelector(".menu-list-section");
	let menuList = menuListSection.querySelector(".menu-list");

	let tabSection = document.querySelector(".tab-section");

	let searchSection = document.querySelector(".search-section");
	let searchInput = searchSection.querySelector("input[name=q]");
	let searchButton = searchSection.querySelector(".icon-search");

	menuList.onclick = function(e) {

		let el = e.target;
		if (!el.classList.contains('icon-heart')) // 하트클래스중에  하트아이콘이 아니면 , 하트아이콘이면 실행 
			// 모든하트 빈하트, 채운하트 
			return;

		e.preventDefault();

		/*let method = "POST";*/
		let { memberId, menuId } = el.dataset;

		//like삭제
		if (el.classList.contains("icon-heart-fill")) {
			fetch(`/api/menulikes/${menuId}/members/${memberId}`, { // api 컨트롤러로 간다. 
				method: "DELETE"
			})
				.then(response => response.text())//object 타입의 텍스트  //1이 like니까 
				.then(value => parseInt(value)) // 1 이면 
				.then(result => {
					if (result == 1) {
						el.classList.remove("icon-heart-fill"); //제거해줘 
						fetch(`/api/menulikes/count?mn=${menuId}`)
							.then(response => response.text())
							.then(value => parseInt(value))
							.then(count => {
								el.nextElementSibling.innerText = count;
								console.log(`count is ${count}`);
							});
					}
				});
		}
		//like 추가
		else {
			let data = `mb=${memberId}&mn=${menuId}` // 이 형식으로
			console.log(data)
			//   console.log('하트');
			fetch("/api/menulikes", {
				method: 'POST', //헤더에 메시지를 보내고, 바디에 내용을 보낸다. 
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded' //url에 코드에 넣는다 . 
				},
				body: new URLSearchParams(data) //위에서 정의한 data형식을 넣어준다. 컨텐츠 타입은 위 
			})
				.then(response => response.text())
				.then(value => parseInt(value))
				.then(result => {
					//console.log(result == 1); // 1이면 like 다, 
					el.classList.add("icon-heart-fill"); 
					if (result == 1) {
						fetch(`/api/menulikes/count?mn=${menuId}`)
							.then(response => response.text())
							.then(value => parseInt(value))
							.then(count => {
								el.nextElementSibling.innerText = count; // HTML에서 좋아요 수를 업데이트합니다.
								console.log(`count is ${count}`);
							});
					}

				});

		}
	}

	searchButton.onclick = (e) => {
		e.preventDefault();
		let querytext = searchInput.value;
		console.log(querytext);
		menuList.innerHTML = "";

		menuListLoad(`http://localhost:8080/api/menus?q=${querytext}`);
	};

	tabSection.onclick = function(e) {
		e.preventDefault();

		if (e.target.tagName !== 'A')
			return;

		console.log(e.target.dataset.id);

		menuListLoad(`http://localhost:8080/api/menus?c=${e.target.dataset.id}`);

	}


});

 

 

 

 

 

 

- 다른 페이지에서도 좋아요를 할수있게 설정한것... 이 데이터를 심어주는 과정이 없으면 메인 페이지에서만 좋아요가 가능하고 다른페이지에서는 안된다

 <a href="detail?id=${menu.id}" 
    data-member-id="919"
    data-menu-id="${menu.id}"
    class="icon icon-heart" ${menu.like ? 'icon-heart-fill' : ''}"
 ></a>

 

 

 

 


x가 0보다 큰 경우에는 "x는 양수입니다."라는 메시지가 출력되고,
그렇지 않은 경우에는 "x는 음수이거나 0입니다."라는 메시지가 출력됩니다.
이렇게 조건에 따라 프로그램의 실행 경로를 다르게 설정하는 것을 "분기를 태운다"고 표현할 수 있습니다.

 

 

 

 

- 이 코드는 사용자의 회원 ID를 숨겨진(hidden) 입력 필드에 설정하고,

해당 회원 ID를 사용하여 좋아요 아이콘 링크에 데이터 속성으로 추가하는 로직임

//list.html
<input id="input-member-id" type="hidden" th:value="${#authentication.principal.id}">

//list.js
let mid = document.querySelector("#input-member-id").value;

<a href="detail?id=${menu.id}" 
    data-member-id="1"
    data-menu-id="${mid}"
    class="icon icon-heart" ${menu.like ? 'icon-heart-fill' : ''}"
     ></a>

 

 

 

 

 

- 지금 하고 있는건 프론트 처럼 보이지만 백엔드 기반이다

 

 

- 인증은 프론트에서 다 한다

 

 

 

 

 

 

 

 

 

728x90

'국비수업 > 수업정리' 카테고리의 다른 글

RestController / 7  (0) 2023.06.23
RestController / 6  (0) 2023.06.22
RestController / 4  (0) 2023.06.20
RestController / 3  (0) 2023.06.19
RestController / 2  (0) 2023.06.16