Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- @ConfigurationProperties
- OAuth2
- 정적 리소스
- rest api
- WebApplication Type
- AuthenticationPrincipal
- EnableAutoConfiguration
- 백기선
- 외부설정
- 리소스핸들러
- Application Runner
- JPA
- @Profile
- Spring Security
- 스프링부트
- application.properties
- cors
- 백준
- webjar
- 리소스 서버
- 다익스트라
- HttpMessageConverters
- Application Argument
- HATEOAS
- 브루트포스
- 알고리즘
- 스프링 부트
- 백트래킹
- JsonSerializer
- Application Event
Archives
- Today
- Total
아카이브
[스프링 기반 REST API 개발] API Index Handler, ErrorsResource 추가하기 본문
Spring/스프링 기반 REST API 개발
[스프링 기반 REST API 개발] API Index Handler, ErrorsResource 추가하기
주멘이 2021. 1. 6. 23:19Index Handler는 다른 리소스에 대한 링크를 제공한다.(EventController 및 문서화)
@RestController
public class IndexController {
@GetMapping("/api")
public RepresentationModel index() {
RepresentationModel index = new RepresentationModel();
index.add(linkTo(EventController.class).withRel("events"));
return index;
}
}
ErrorResource 작성 : 에러 발생 시 Index 링크 제공
public class ErrorsResource extends EntityModel<Errors> {
public ErrorsResource(Errors errors, Link... links) {
super(errors, links);
add(linkTo(methodOn(IndexController.class).index()).withRel("index"));
}
}
EventController 수정하기 (리팩토링)
@PostMapping
public ResponseEntity createEvent(@RequestBody @Valid EventDto eventDto, Errors errors) {
if (errors.hasErrors()) {
return badRequest(errors);
}
eventValidator.validate(eventDto, errors);
if (errors.hasErrors()) {
return badRequest(errors); // errors는 java bean spec을 준수한 것이 아니라, serialize 불가 --> ErrorsSerializer를 objectMapper에 등록해주면, json으로 받을 수 있다
}
Event event = modelMapper.map(eventDto, Event.class);
event.update();
Event newEvent = this.eventRepository.save(event);
WebMvcLinkBuilder selfLinkBuilder = linkTo(EventController.class).slash(newEvent.getId());
URI createdUri = selfLinkBuilder.toUri();
/* HATEOAS links add */
EventResource eventResource = new EventResource(event);
eventResource.add(linkTo(EventController.class).withRel("query-events"));
eventResource.add(selfLinkBuilder.withRel("update-event"));
eventResource.add(new Link("/docs/index.html#resources-events-create").withRel("profile"));
return ResponseEntity.created(createdUri).body(eventResource);
}
private ResponseEntity<ErrorsResource> badRequest(Errors errors) {
return ResponseEntity.badRequest().body(new ErrorsResource(errors));
}
'Spring > 스프링 기반 REST API 개발' 카테고리의 다른 글
[스프링 기반 REST API 개발] 이벤트 조회 API 구현하기 (0) | 2021.01.09 |
---|---|
[스프링 기반 REST API 개발] 이벤트 목록 조회 API 구현 (0) | 2021.01.09 |
[스프링 기반 REST API 개발] 테스트용 DB와 설정 분리하기 (0) | 2021.01.06 |
[스프링 기반 REST API 개발] Spring REST Docs 문서 빌드하기 (0) | 2021.01.06 |
[스프링 기반 REST API 개발] Request/Response 필드와 헤더 문서화하기 (0) | 2021.01.06 |