package io.spring.api; import com.fasterxml.jackson.annotation.JsonRootName; import io.spring.api.exception.InvalidRequestException; import io.spring.application.article.ArticleQueryService; import io.spring.core.article.Article; import io.spring.core.article.ArticleRepository; import io.spring.core.user.User; import lombok.Getter; import lombok.NoArgsConstructor; import org.hibernate.validator.constraints.NotBlank; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; @RestController @RequestMapping(path = "/articles") public class ArticlesApi { private ArticleRepository articleRepository; private ArticleQueryService articleQueryService; @Autowired public ArticlesApi(ArticleRepository articleRepository, ArticleQueryService articleQueryService) { this.articleRepository = articleRepository; this.articleQueryService = articleQueryService; } @PostMapping public ResponseEntity createArticle(@Valid @RequestBody NewArticleParam newArticleParam, BindingResult bindingResult, @AuthenticationPrincipal User user) { if (bindingResult.hasErrors()) { throw new InvalidRequestException(bindingResult); } Article article = new Article( newArticleParam.getTitle(), newArticleParam.getDescription(), newArticleParam.getBody(), newArticleParam.getTagList(), user.getId()); articleRepository.save(article); return ResponseEntity.ok(articleQueryService.findById(article.getId(), user).get()); } } @Getter @JsonRootName("article") @NoArgsConstructor class NewArticleParam { @NotBlank(message = "can't be empty") private String title; @NotBlank(message = "can't be empty") private String description; @NotBlank(message = "can't be empty") private String body; private String[] tagList; }