6.1 REST 컨트롤러 작성하기

이번 장부터 UI 및 프론트는 앵귤러 소스코드로 대체한다. 앵귤러 소스코드 예제 다운로드 및 실행은 6.4절을 참고하자.

6.1.1 서버에서 데이터 가져오기

@RestController
@RequestMapping(value = "/design", produces = MediaType.APPLICATION_JSON_VALUE)
//@SessionAttributes("order")
@CrossOrigin("*")
public class DesignTacoController {
		
		...
    
    @GetMapping("/recent")
    public Iterable<Taco> recentTacos() {
        PageRequest page = PageRequest.of(0, 12, Sort.by("createdAt").descending());
        return tacoRepo.findAll(page).getContent();
    }
}

타코 ID로 특정 타코만 가져오는 엔드포인트

@GetMapping("/{id}")
public ResponseEntity<Taco> tacoById(@PathVariable("id") Long id) {
		Optional<Taco> optTaco = tacoRepo.findById(id);
    return optTaco.map(taco -> new ResponseEntity<>(taco, HttpStatus.OK))
        .orElseGet(() -> new ResponseEntity<>(null, HttpStatus.NOT_FOUND));
}

아래와 같이 curl이나, HTTPie로 요청을 보내보자.