Skip to content

Commit

Permalink
#53 refactor: rest api로 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
dbwp031 committed Oct 10, 2023
1 parent c18c24a commit 09f95ae
Show file tree
Hide file tree
Showing 11 changed files with 189 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,16 @@
import com.example.ourworldcup.dto.VsResultDto;
import com.example.ourworldcup.repository.WorldcupRepository;
import com.example.ourworldcup.service.game.GameService;
import com.example.ourworldcup.service.worldcup.WorldcupService;
import com.example.ourworldcup.service.item.ItemService;
import com.example.ourworldcup.service.worldcup.WorldcupService;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RequiredArgsConstructor
Expand Down Expand Up @@ -62,8 +60,7 @@ public String renderWorldcupAddItemCreationForm() {
@GetMapping("/new/items")
public String renderWorldcupItemsCreationForm(ModelMap map, HttpSession httpSession) throws Exception {
Worldcup sessionWorldcup = (Worldcup) httpSession.getAttribute(SESSION_ATTR_WORLDCUP);
Worldcup worldcup = worldcupService.findById(sessionWorldcup.getId())
.orElseThrow(() -> new IllegalArgumentException("해당 id의 월드컵이 존재하지 않습니다"));
Worldcup worldcup = worldcupService.findById(sessionWorldcup.getId());
WorldcupResponseDto.WorldcupItemsDto worldcupItemsDto = new WorldcupResponseDto.WorldcupItemsDto();
List<WorldcupResponseDto.WorldcupItemDto> itemsDto = worldcup.getItems().stream().map(a -> {
try {
Expand Down Expand Up @@ -123,7 +120,7 @@ public String saveImageItems_redirectWorldcupItemCreationForm(
@GetMapping("/{worldcupId}/details")
public String renderWorldcupDetails(@PathVariable Long worldcupId,
ModelMap modelMap) {
Worldcup worldcup = worldcupService.findById(worldcupId).get();
Worldcup worldcup = worldcupService.findById(worldcupId);
WorldcupResponseDto.BasicDto worldcupResponseBaseDto = WorldcupConverter.toWorldcupResponseBasicDto(worldcup);
modelMap.addAttribute("worldcupDto", worldcupResponseBaseDto);
return "worldcup/detail";
Expand All @@ -132,23 +129,25 @@ public String renderWorldcupDetails(@PathVariable Long worldcupId,
@GetMapping("/{worldcupId}/members")
public String renderWorldcupMembers(@PathVariable Long worldcupId,
ModelMap modelMap) {
Optional<Worldcup> worldcup = worldcupService.findById(worldcupId);
if (worldcup.isPresent()) {
WorldcupResponseDto.MembersDto worldcupResponseMembersDto = WorldcupConverter.toWorldcupResponseMembersDto(worldcup.get());
modelMap.addAttribute("worldcupDto", worldcupResponseMembersDto);
return "worldcup/members";
}
return "error";
}

Worldcup worldcup = worldcupService.findById(worldcupId);
WorldcupResponseDto.MembersDto worldcupResponseMembersDto = WorldcupConverter.toWorldcupResponseMembersDto(worldcup);
modelMap.addAttribute("worldcupDto", worldcupResponseMembersDto);
return "worldcup/members";
}

/*
* 특정 월드컵에 대한 게임을 만드는 것이기 때문에 Worldcup - Game의 계층관계가 명확하다.
* 이렇게 명확할 때에는 path variable을 사용한다.
*
* 그렇지 않을 경우엔 query paramter을 사용할 수 있다.
* */
@GetMapping("/{worldcupId}/game/new")
public String renderGameSettingPage(@PathVariable Long worldcupId,
ModelMap modelMap) {
List<Integer> roundTypes = worldcupService.getRoundTypes(worldcupId);
String worldcupTitle = worldcupService.getTitle(worldcupId);
modelMap.addAttribute("worldcupId", worldcupId);
modelMap.addAttribute("worldcupTitle", worldcupTitle);
modelMap.addAttribute("roundTypes", roundTypes);
public String renderGameSettingPage() {
// List<Integer> roundTypes = worldcupService.getRoundTypes(worldcupId);
// String worldcupTitle = worldcupService.getTitle(worldcupId);
// modelMap.addAttribute("worldcupId", worldcupId);
// modelMap.addAttribute("worldcupTitle", worldcupTitle);
// modelMap.addAttribute("roundTypes", roundTypes);
return "game/setting";
}

Expand All @@ -164,7 +163,7 @@ public String createGame(@PathVariable Long worldcupId,
@GetMapping("/{worldcupId}/games")
public String renderGamesPage(@PathVariable Long worldcupId,
ModelMap modelMap) {
WorldcupResponseDto.GamesDto gamesDto = WorldcupConverter.toWorldcupResponseGamesDto(worldcupService.findById(worldcupId).orElseThrow(() -> new IllegalArgumentException("해당 월드컵 id가 존재하지 않습니다")));
WorldcupResponseDto.GamesDto gamesDto = WorldcupConverter.toWorldcupResponseGamesDto(worldcupService.findById(worldcupId));
modelMap.addAttribute("gamesDto", gamesDto);
return "worldcup/games";
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
package com.example.ourworldcup.controller.worldcup;

import com.example.ourworldcup.auth.AuthUser;
import com.example.ourworldcup.controller.worldcup.dto.WorldcupResponseDto;
import com.example.ourworldcup.converter.worldcup.WorldcupConverter;
import com.example.ourworldcup.domain.Worldcup;
import com.example.ourworldcup.domain.constant.PickType;
import com.example.ourworldcup.domain.game.Game;
import com.example.ourworldcup.domain.userAccount.UserAccount;
import com.example.ourworldcup.service.game.GameService;
import com.example.ourworldcup.service.item.ItemService;
import com.example.ourworldcup.service.member.MemberService;
import com.example.ourworldcup.service.worldcup.WorldcupService;
Expand All @@ -9,10 +16,7 @@
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
Expand All @@ -26,6 +30,7 @@ public class WorldcupRestController {
private final WorldcupService worldcupService;
private final ItemService itemService;
private final MemberService memberService;
private final GameService gameService;

@DeleteMapping("/item/{id}")
public ResponseEntity<Map<String, Boolean>> deleteItem(@PathVariable Long id, HttpSession session, HttpServletResponse response) {
Expand All @@ -47,4 +52,34 @@ public ResponseEntity<Map<String, Boolean>> deleteMember(@PathVariable Long id)

return new ResponseEntity<>(responseMap, HttpStatus.OK);
}

@GetMapping("/{worldcupId}/roundTypes")
public ResponseEntity<WorldcupResponseDto.RoundTypesDto> getRoundTypes(@PathVariable Long worldcupId) {
Worldcup worldcup = worldcupService.findById(worldcupId);
return ResponseEntity.ok(WorldcupConverter.toWorldcupResponseRoundTypesDto(worldcup));
}

@PostMapping("/{worldcupId}/game")
public ResponseEntity<Map<String, Long>> createGame(@PathVariable Long worldcupId,
@RequestParam Long initRound,
@AuthUser UserAccount userAccount) {

Game game = gameService.createGame(userAccount.getId(), worldcupId, initRound, PickType.ORDER);
Map<String, Long> responseMap = new HashMap<>();
System.out.println("GAME");
System.out.println(game.getId());
responseMap.put("gameId", game.getId());

return new ResponseEntity<>(responseMap, HttpStatus.OK);
}
}


// @GetMapping("/{worldcupId}/game/new/round/{round}")
// public String createGame(@PathVariable Long worldcupId,
// @PathVariable(value = "round") Long initialRound,
// Authentication authentication) {
// JwtAuthentication jwtAuthentication = (JwtAuthentication) authentication;
// Game game = gameService.createGame(jwtAuthentication.getPrincipalDetails().getId(), worldcupId, initialRound, PickType.ORDER);
// return String.format("redirect:/game/%d", game.getId());
// }
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,17 @@ public static class WorldcupItemsDto {
@Builder.Default
private List<WorldcupItemDto> items = new ArrayList<>();
}

@Builder
@Setter
@Getter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public static class RoundTypesDto {
private Long id;
private String title;
private String content;
private List<Integer> roundTypes;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.example.ourworldcup.domain.constant.RoundType;
import com.example.ourworldcup.service.game.GameService;
import com.example.ourworldcup.service.invitation.InvitationService;
import com.example.ourworldcup.service.worldcup.WorldcupService;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
Expand All @@ -20,13 +21,16 @@
public class WorldcupConverter {
private final InvitationService invitationService;
private final GameService gameService;
private final WorldcupService worldcupService;
private static InvitationService staticInvitationService;
private static GameService staticGameService;
private static WorldcupService staticWorldcupService;

@PostConstruct
public void init() {
staticInvitationService = invitationService;
staticGameService = gameService;
staticWorldcupService = worldcupService;
}

public static WorldcupResponseDto.BasicDto toWorldcupResponseBasicDto(Worldcup worldcup) {
Expand Down Expand Up @@ -73,4 +77,15 @@ public static WorldcupResponseDto.GamesDto toWorldcupResponseGamesDto(Worldcup w
.games(games)
.build();
}

public static WorldcupResponseDto.RoundTypesDto toWorldcupResponseRoundTypesDto(Worldcup worldcup) {
List<Integer> roundTypes = staticWorldcupService.getRoundTypes(worldcup.getId());

return WorldcupResponseDto.RoundTypesDto.builder()
.id(worldcup.getId())
.title(worldcup.getTitle())
.content(worldcup.getContent())
.roundTypes(roundTypes)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import com.example.ourworldcup.repository.item.ItemRepository;
import com.example.ourworldcup.service.game.GameService;
import com.example.ourworldcup.service.item.ItemService;
import com.example.ourworldcup.service.worldcup.WorldcupService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -26,7 +27,7 @@
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

@Transactional
@Transactional(readOnly = true)
@RequiredArgsConstructor
@Service
public class GameServiceImpl implements GameService {
Expand All @@ -36,9 +37,16 @@ public class GameServiceImpl implements GameService {
private final GameRepository gameRepository;
private final ItemRepository itemRepository;
private final ItemService itemService;
private final WorldcupService worldcupService;

@Transactional
@Override
public Game createGame(Long userAccountId, Long worldcupId, Long initialRound, PickType pickType) {

if (!worldcupService.getRoundTypes(worldcupId).contains(initialRound.intValue())) {
throw new IllegalArgumentException("해당 initialRound는 올바르지 않습니다.");
}

UserAccount userAccount = userAccountRepository.getReferenceById(userAccountId);
Worldcup worldcup = worldcupRepository.findById(worldcupId)
.orElseThrow(() -> new IllegalArgumentException("월드컵 아이디가 잘못됐습니다."));
Expand Down Expand Up @@ -67,6 +75,7 @@ public Game findById(Long id) {
.orElseThrow(() -> new IllegalArgumentException("Game 아이디가 존재하지 않습니다."));
}

@Transactional
@Override
public List<Round> initializeRounds(Worldcup worldcup, Game game, Long roundType, PickType pickType) {
List<Item> items = worldcup.getItems();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import com.example.ourworldcup.domain.userAccount.UserAccount;

import java.util.List;
import java.util.Optional;

public interface WorldcupService {
Worldcup createWorldcup(WorldcupRequestDto.WorldcupCreateRequestDto worldcupCreateRequestDto, UserAccount userAccount);
Expand All @@ -18,7 +17,7 @@ public interface WorldcupService {

void enrollUserAccount(Invitation invitation, UserAccount userAccount, MemberRole memberRole);

Optional<Worldcup> findById(Long worldcupId);
Worldcup findById(Long worldcupId);

List<Integer> getRoundTypes(Long id);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


/*
Expand Down Expand Up @@ -93,16 +92,15 @@ public void enrollUserAccount(Invitation invitation, UserAccount userAccount, Me
* */

@Override
public Optional<Worldcup> findById(Long worldcupId) {
return worldcupRepository.findById(worldcupId);
public Worldcup findById(Long worldcupId) {
return worldcupRepository.findById(worldcupId)
.orElseThrow(() -> new IllegalArgumentException("해당 worldcupId가 없습니다."));
}

@Override
public List<Integer> getRoundTypes(Long id) {
em.flush();
Worldcup worldcup = worldcupRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("존재하지 않는 월드컵의 id입니다."));

Worldcup worldcup = this.findById(id);
Integer itemsSize = worldcup.getItems().size();
System.out.println("itemsSize: " + itemsSize);
System.out.println(worldcup);
Expand All @@ -123,8 +121,7 @@ public List<Integer> getRoundTypes(Long id) {

@Override
public String getTitle(Long id) {
Worldcup worldcup = worldcupRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("존재하지 않는 월드컵의 id입니다."));
Worldcup worldcup = this.findById(id);
return worldcup.getTitle();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
@RequiredArgsConstructor
@Component
public class WorldcupExistValidator implements ConstraintValidator<ExistWorldcup, Long> {
private static final ThreadLocal<Long> worldcupIdHolder = new ThreadLocal<>();
private final WorldcupRepository worldcupRepository;
private static WorldcupRepository staticWorldcupRepository;

Expand Down
70 changes: 70 additions & 0 deletions src/main/resources/static/js/game/v1/new/setting.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
$(document).ready(function () {
const pathSegments = window.location.pathname.split('/');
const worldcupId = pathSegments[2]; // '12345'
console.log(worldcupId);
getRoundTypes(worldcupId);

let roundType = null;
$("#roundTypesContainer").on("click", "button", function () {
roundType = $(this).data("round-type");
selectRoundTypes(worldcupId, roundType)
});

}
);

function selectRoundTypes(worldcupId, roundType) {

$.ajax({
url: `/api/v1/worldcup/${worldcupId}/game?initRound=${roundType}`,
type: 'POST',
contentType: `application/json`,
success: function (data, textStatus, xhr) {
console.log(data.gameId);
redirect(`/game/${data.gameId}`); //TODO: 설정해줘야됨

},
error: function () {
alert("selectRoundTypes Error");
},

})
}

function getRoundTypes(worldcupId) {
$.ajax({
url: `/api/v1/worldcup/${worldcupId}/roundTypes`,
type: "GET",
dataType: "json",
success: function (data, textStatus, xhr) {
renderPage(data, worldcupId);
console.log("success");
},
error: function () {
alert("getRoundTypes Error");
},
})
}

function renderPage(data, worldcupId) {
let roundTypes = data.roundTypes;
let container = $("#roundTypesContainer");

$("#worldcup-title").text(data.title);
roundTypes.forEach(round => {
let btnDiv = $("<div></div>").addClass("text-center");
let btn = $("<button></button>")
.text(`${round}강`)
.attr("data-round-type", round)
.attr("id", `round-type-${round}`)
container.append(btnDiv.append(btn));
})
}

function redirect(targetUrl) {
window.location.href = getBaseUrl() + targetUrl;
}

function getBaseUrl() {
return window.location.protocol + "//" + window.location.host;
}
Loading

0 comments on commit 09f95ae

Please sign in to comment.