diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..c2065bc26 --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..5ba842de7 --- /dev/null +++ b/build.gradle @@ -0,0 +1,83 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '2.7.14' + id 'io.spring.dependency-management' version '1.0.15.RELEASE' + id 'org.asciidoctor.jvm.convert' version '3.3.2' +} + +group = 'com.prgrms' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + asciidoctorExtensions + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +ext { + set('snippetsDir', file("build/generated-snippets")) +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.h2database:h2' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + + testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' + implementation 'org.springframework.restdocs:spring-restdocs-asciidoctor' +} + +tasks.named('test') { + outputs.dir snippetsDir + useJUnitPlatform() +} + +tasks.named('asciidoctor') { + inputs.dir snippetsDir + dependsOn test +} + +task copyDocument(type: Copy) { + dependsOn asciidoctor + from file("build/docs/asciidoc") + into file("src/main/resources/static/docs") +} + +asciidoctor.doFirst { + delete file('src/main/resources/static/docs') +} + +build { + dependsOn copyDocument +} + +bootJar { + dependsOn copyDocument + from "${asciidoctor.outputDir}" + into 'static/docs' + +} + +asciidoctor { + dependsOn test + configurations 'asciidoctorExtensions' + inputs.dir snippetsDir + + sources { + include("**/index.adoc", "**/common/*.adoc") + } + baseDirFollowsSourceFile() +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..033e24c4c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..9f4197d5f --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 000000000..fcb6fca14 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..2152237a5 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'board-jpa' diff --git a/src/docs/asciidoc/index.adoc b/src/docs/asciidoc/index.adoc new file mode 100644 index 000000000..7ff53e7ed --- /dev/null +++ b/src/docs/asciidoc/index.adoc @@ -0,0 +1,119 @@ +ifndef::snippets[] +:snippets: ../../../build/generated-snippets +endif::[] + += REST Docs 게시판 API +:doctype: book +:icons: font +:source-highlighter: highlightjs +:toc: left +:toclevels: 2 +:sectlinks: + +[[User-API]] + +== User API + +=== 유저 등록 + +==== /api/v1/users + +.Request +include::{snippets}/user-join/http-request.adoc[] + +include::{snippets}/user-join/request-fields.adoc[] + +.Response +include::{snippets}/user-join/http-response.adoc[] + +include::{snippets}/user-join/response-fields.adoc[] + +.Request Fail - 중복된 유저 이름 +include::{snippets}/user-join-fail-duplicated-name/http-response.adoc[] + +include::{snippets}/user-join-fail-duplicated-name/response-fields.adoc[] + +.Request Fail - 잘못된 데이터 입력 +include::{snippets}/user-join-fail-invalid-data/http-request.adoc[] + +include::{snippets}/user-join-fail-invalid-data/request-fields.adoc[] + +include::{snippets}/user-join-fail-invalid-data/http-response.adoc[] + +include::{snippets}/user-join-fail-invalid-data/response-fields.adoc[] + +[[Post-API]] +== Post API + +=== 게시물 등록 + +==== /api/v1/posts +.Request +include::{snippets}/post-create/http-request.adoc[] + +include::{snippets}/post-create/request-fields.adoc[] + +.Response +include::{snippets}/post-create/http-response.adoc[] + +include::{snippets}/post-create/response-fields.adoc[] + +.Request Fail - 존재하지 않는 유저 +include::{snippets}/post-create-fail-not-found-user/http-response.adoc[] + +include::{snippets}/post-create-fail-not-found-user/response-fields.adoc[] + +.Request Fail - 잘못된 데이터 입력 +include::{snippets}/post-create-fail-invalid-data/http-response.adoc[] + +include::{snippets}/post-create-fail-invalid-data/response-fields.adoc[] + + +=== 게시물 전체 조회 + +==== /api/v1/posts + +.Response +include::{snippets}/post-get-all/http-response.adoc[] + +include::{snippets}/post-get-all/response-fields.adoc[] + +=== 게시물 단건 조회 + +==== /api/v1/posts/{id} + +.Request +include::{snippets}/post-get-one/http-request.adoc[] + +include::{snippets}/post-get-one/path-parameters.adoc[] + +.Response +include::{snippets}/post-get-one/http-response.adoc[] + +include::{snippets}/post-get-one/response-fields.adoc[] + +.Request Fail - 존재하지 않는 게시물 +include::{snippets}/post-get-one-fail-not-found-post/http-response.adoc[] + +include::{snippets}/post-get-one-fail-not-found-post/response-fields.adoc[] + +=== 게시물 수정 + +==== /api/v1/posts/{id} + +.Request +include::{snippets}/post-update/http-request.adoc[] + +include::{snippets}/post-update/path-parameters.adoc[] + +include::{snippets}/post-update/request-fields.adoc[] + +.Response +include::{snippets}/post-update/http-response.adoc[] + +include::{snippets}/post-update/response-fields.adoc[] + +.Request Fail - 존재하지 않는 게시물 +include::{snippets}/post-update-fail-not-found-post/http-response.adoc[] + +include::{snippets}/post-update-fail-not-found-post/response-fields.adoc[] \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/BoardJpaApplication.java b/src/main/java/com/prgrms/boardjpa/BoardJpaApplication.java new file mode 100644 index 000000000..296412952 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/BoardJpaApplication.java @@ -0,0 +1,13 @@ +package com.prgrms.boardjpa; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BoardJpaApplication { + + public static void main(String[] args) { + SpringApplication.run(BoardJpaApplication.class, args); + } + +} diff --git a/src/main/java/com/prgrms/boardjpa/Post/application/PostService.java b/src/main/java/com/prgrms/boardjpa/Post/application/PostService.java new file mode 100644 index 000000000..f8502de0c --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/Post/application/PostService.java @@ -0,0 +1,79 @@ +package com.prgrms.boardjpa.Post.application; + +import com.prgrms.boardjpa.Post.domain.Post; +import com.prgrms.boardjpa.Post.domain.PostRepository; +import com.prgrms.boardjpa.Post.dto.request.PostCreateRequest; +import com.prgrms.boardjpa.Post.dto.request.PostUpdateRequest; +import com.prgrms.boardjpa.Post.dto.response.PostListResponse; +import com.prgrms.boardjpa.Post.dto.response.PostResponse; +import com.prgrms.boardjpa.User.domain.User; +import com.prgrms.boardjpa.User.domain.UserRepository; +import com.prgrms.boardjpa.global.ErrorCode; +import com.prgrms.boardjpa.global.exception.BusinessServiceException; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@RequiredArgsConstructor +@Service +public class PostService { + + private final PostRepository postRepository; + private final UserRepository userRepository; + + @Transactional + public PostResponse create(PostCreateRequest createRequest) { + User user = userRepository.findById(createRequest.getUserId()) + .orElseThrow(() -> new BusinessServiceException(ErrorCode.NOT_FOUND_USER)); + + Post post = createRequest.toEntity(); + post.updateUser(user); + Post savedPost = postRepository.save(post); + + return PostResponse.create(savedPost); + } + + @Transactional(readOnly = true) + public PostResponse findOne(Long id) { + Post post = postRepository.findById(id) + .orElseThrow(() -> new BusinessServiceException(ErrorCode.NOT_FOUND_POST)); + + return PostResponse.create(post); + } + + @Transactional(readOnly = true) + public PostListResponse findAll(Pageable pageable) { + Page postList = postRepository.findAll(pageable); + List postResponseList = postList + .stream() + .map(PostResponse::create) + .toList(); + + return PostListResponse.create(postResponseList); + } + + @Transactional + public PostResponse update(Long postId, PostUpdateRequest updateRequest) { + Post post = postRepository.findById(postId) + .orElseThrow(() -> new BusinessServiceException(ErrorCode.NOT_FOUND_POST)); + + User user = userRepository.findById(post.getUser().getId()) + .orElseThrow(() -> new BusinessServiceException(ErrorCode.NOT_FOUND_USER)); + + checkAuthorAndModifier(user.getId(), post.getUser().getId()); + + post.update(updateRequest.title(), updateRequest.content()); + + return PostResponse.create(post); + } + + private static void checkAuthorAndModifier(Long modifierId, Long authorId) { + if (modifierId != authorId) { + throw new BusinessServiceException(ErrorCode.NOT_MATCH_AUTHOR_MODIFIER); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/Post/domain/Post.java b/src/main/java/com/prgrms/boardjpa/Post/domain/Post.java new file mode 100644 index 000000000..349ef94d7 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/Post/domain/Post.java @@ -0,0 +1,52 @@ +package com.prgrms.boardjpa.Post.domain; + +import com.prgrms.boardjpa.User.domain.User; +import com.prgrms.boardjpa.global.domain.BaseEntity; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Entity +public class Post extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + @Column(name = "post_id") + private Long id; + + @Column(nullable = false) + private String title; + + @Lob + @Column(nullable = false) + private String content; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + @Builder + public Post(String title, String content) { + this.title = title; + this.content = content; + } + + public void updateUser(User author) { + this.user = author; + } + + public void update(String updateTitle, String updateContent) { + if (updateTitle != null) { + this.title = updateTitle; + } + + if (updateContent != null) { + this.content = updateContent; + } + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/Post/domain/PostRepository.java b/src/main/java/com/prgrms/boardjpa/Post/domain/PostRepository.java new file mode 100644 index 000000000..d4c70d967 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/Post/domain/PostRepository.java @@ -0,0 +1,6 @@ +package com.prgrms.boardjpa.Post.domain; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PostRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/Post/dto/request/PostCreateRequest.java b/src/main/java/com/prgrms/boardjpa/Post/dto/request/PostCreateRequest.java new file mode 100644 index 000000000..2e939e552 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/Post/dto/request/PostCreateRequest.java @@ -0,0 +1,39 @@ +package com.prgrms.boardjpa.Post.dto.request; + +import com.prgrms.boardjpa.Post.domain.Post; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Getter +public class PostCreateRequest { + + private Long userId; + + @NotBlank(message = "제목을 입력해 주세요.") + @Size(min = 2, message = "제목은 2글자 이상 입력해주세요.") + private String title; + + @NotBlank(message = "내용을 입력해 주세요.") + @Size(min = 2, message = "내용은 2글자 이상 입력해주세요.") + private String content; + + @Builder + public PostCreateRequest(Long userId, String title, String content) { + this.userId = userId; + this.title = title; + this.content = content; + } + + public Post toEntity() { + return Post.builder() + .title(title) + .content(content) + .build(); + } +} diff --git a/src/main/java/com/prgrms/boardjpa/Post/dto/request/PostUpdateRequest.java b/src/main/java/com/prgrms/boardjpa/Post/dto/request/PostUpdateRequest.java new file mode 100644 index 000000000..c5a32f1ac --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/Post/dto/request/PostUpdateRequest.java @@ -0,0 +1,4 @@ +package com.prgrms.boardjpa.Post.dto.request; + +public record PostUpdateRequest(String title, String content) { +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/Post/dto/response/PostListResponse.java b/src/main/java/com/prgrms/boardjpa/Post/dto/response/PostListResponse.java new file mode 100644 index 000000000..7bf2aa59c --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/Post/dto/response/PostListResponse.java @@ -0,0 +1,10 @@ +package com.prgrms.boardjpa.Post.dto.response; + +import java.util.List; + +public record PostListResponse(List postResponseList) { + + public static PostListResponse create(List postResponseList) { + return new PostListResponse(postResponseList); + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/Post/dto/response/PostResponse.java b/src/main/java/com/prgrms/boardjpa/Post/dto/response/PostResponse.java new file mode 100644 index 000000000..bdf5619a6 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/Post/dto/response/PostResponse.java @@ -0,0 +1,11 @@ +package com.prgrms.boardjpa.Post.dto.response; + +import com.prgrms.boardjpa.Post.domain.Post; + +public record PostResponse(Long id, String title, String content, Long authorId) { + + public static PostResponse create(Post post) { + return new PostResponse(post.getId(), post.getTitle(), post.getContent(), post.getUser().getId()); + } + +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/Post/presentation/PostApiController.java b/src/main/java/com/prgrms/boardjpa/Post/presentation/PostApiController.java new file mode 100644 index 000000000..85b64e8e9 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/Post/presentation/PostApiController.java @@ -0,0 +1,49 @@ +package com.prgrms.boardjpa.Post.presentation; + +import com.prgrms.boardjpa.Post.application.PostService; +import com.prgrms.boardjpa.Post.dto.request.PostCreateRequest; +import com.prgrms.boardjpa.Post.dto.request.PostUpdateRequest; +import com.prgrms.boardjpa.Post.dto.response.PostListResponse; +import com.prgrms.boardjpa.Post.dto.response.PostResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +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; + +@RestController +@RequestMapping("/api/v1/posts") +@RequiredArgsConstructor +public class PostApiController { + + private final PostService postService; + + @PostMapping + public ResponseEntity create(@Validated @RequestBody PostCreateRequest createRequest) { + return ResponseEntity.ok(postService.create(createRequest)); + } + + @GetMapping + public ResponseEntity findAll(@PageableDefault(size = 5, sort = "id", + direction = Sort.Direction.DESC) Pageable pageable) { + return ResponseEntity.ok(postService.findAll(pageable)); + } + + @GetMapping("/{id}") + public ResponseEntity findOne(@PathVariable("id") Long postId) { + return ResponseEntity.ok(postService.findOne(postId)); + } + + @PatchMapping("/{id}") + public ResponseEntity update(@PathVariable("id") Long postId, @RequestBody PostUpdateRequest updateRequest) { + return ResponseEntity.ok(postService.update(postId, updateRequest)); + } +} diff --git a/src/main/java/com/prgrms/boardjpa/User/application/UserService.java b/src/main/java/com/prgrms/boardjpa/User/application/UserService.java new file mode 100644 index 000000000..fbd1d6576 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/User/application/UserService.java @@ -0,0 +1,35 @@ +package com.prgrms.boardjpa.User.application; + +import com.prgrms.boardjpa.User.domain.User; +import com.prgrms.boardjpa.User.domain.UserRepository; +import com.prgrms.boardjpa.User.dto.UserRequest; +import com.prgrms.boardjpa.User.dto.UserResponse; +import com.prgrms.boardjpa.global.ErrorCode; +import com.prgrms.boardjpa.global.exception.BusinessServiceException; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@RequiredArgsConstructor +@Service +public class UserService { + + private final UserRepository userRepository; + + @Transactional + public UserResponse join(UserRequest request) { + validateDuplicateName(request.getName()); + + User user = request.toEntity(); + User savedUser = userRepository.save(user); + + return UserResponse.create(savedUser); + } + + + private void validateDuplicateName(String name) { + if (userRepository.existsByName(name)) { + throw new BusinessServiceException(ErrorCode.DUPLICATED_NAME); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/User/domain/User.java b/src/main/java/com/prgrms/boardjpa/User/domain/User.java new file mode 100644 index 000000000..5a39c7f32 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/User/domain/User.java @@ -0,0 +1,57 @@ +package com.prgrms.boardjpa.User.domain; + +import com.prgrms.boardjpa.global.ErrorCode; +import com.prgrms.boardjpa.global.domain.BaseEntity; +import com.prgrms.boardjpa.global.exception.InvalidDomainConditionException; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.util.StringUtils; + +import javax.persistence.*; +import java.util.regex.Pattern; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Table(name = "users") +@Entity +public class User extends BaseEntity { + + private static final Pattern NAME_REGEX_PATTERN = Pattern.compile("^[가-힣a-zA-Z0-9]+$"); + private static final int MINIMUM_AGE = 1; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + @Column(name = "user_id") + private Long id; + + @Column(nullable = false, length = 40, unique = true) + private String name; + + private int age; + + private String hobby; + + @Builder + public User(String name, int age, String hobby) { + validateAge(age); + validateName(name); + this.name = name; + this.age = age; + this.hobby = hobby; + } + + private void validateName(String name) { + if (!StringUtils.hasText(name) + || !NAME_REGEX_PATTERN.matcher(name).matches()) { + throw new InvalidDomainConditionException(ErrorCode.INVALID_NAME); + } + } + + private void validateAge(int age) { + if (age < MINIMUM_AGE) { + throw new InvalidDomainConditionException(ErrorCode.INVALID_AGE); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/User/domain/UserRepository.java b/src/main/java/com/prgrms/boardjpa/User/domain/UserRepository.java new file mode 100644 index 000000000..640b6b3ed --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/User/domain/UserRepository.java @@ -0,0 +1,8 @@ +package com.prgrms.boardjpa.User.domain; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { + + boolean existsByName(String name); +} diff --git a/src/main/java/com/prgrms/boardjpa/User/dto/UserRequest.java b/src/main/java/com/prgrms/boardjpa/User/dto/UserRequest.java new file mode 100644 index 000000000..90b28e16c --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/User/dto/UserRequest.java @@ -0,0 +1,42 @@ +package com.prgrms.boardjpa.User.dto; + +import com.prgrms.boardjpa.User.domain.User; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Getter +public class UserRequest { + + @NotBlank(message = "유저 이름을 입력해주세요.") + @Pattern(regexp = "^[a-zA-Z0-9]+$", message = "이름은 영어만 입력가능합니다.") + private String name; + + @Min(value = 1, message = "올바른 나이를 입력해 주세요.") + private int age; + + @Pattern(regexp = "^[가-힣a-zA-Z]+$", message = "취미는 한글/영어만 입력가능합니다.") + @NotBlank(message = "취미를 입력해주세요.") + private String hobby; + + @Builder + public UserRequest(String name, int age, String hobby) { + this.name = name; + this.age = age; + this.hobby = hobby; + } + + public User toEntity() { + return User.builder() + .name(name) + .age(age) + .hobby(hobby) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/User/dto/UserResponse.java b/src/main/java/com/prgrms/boardjpa/User/dto/UserResponse.java new file mode 100644 index 000000000..91f557ed6 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/User/dto/UserResponse.java @@ -0,0 +1,10 @@ +package com.prgrms.boardjpa.User.dto; + +import com.prgrms.boardjpa.User.domain.User; + +public record UserResponse(Long id, String name, int age, String hobby) { + + public static UserResponse create(User user) { + return new UserResponse(user.getId(), user.getName(), user.getAge(), user.getHobby()); + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/User/presentation/UserApiController.java b/src/main/java/com/prgrms/boardjpa/User/presentation/UserApiController.java new file mode 100644 index 000000000..cab3b9886 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/User/presentation/UserApiController.java @@ -0,0 +1,25 @@ +package com.prgrms.boardjpa.User.presentation; + +import com.prgrms.boardjpa.User.application.UserService; +import com.prgrms.boardjpa.User.dto.UserRequest; +import com.prgrms.boardjpa.User.dto.UserResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +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; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/v1/users") +public class UserApiController { + + private final UserService userService; + + @PostMapping + public ResponseEntity join(@Validated @RequestBody UserRequest request) { + return ResponseEntity.ok(userService.join(request)); + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/global/ErrorCode.java b/src/main/java/com/prgrms/boardjpa/global/ErrorCode.java new file mode 100644 index 000000000..5bda378a8 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/global/ErrorCode.java @@ -0,0 +1,26 @@ +package com.prgrms.boardjpa.global; + +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +public enum ErrorCode { + + //고객 + INVALID_AGE(HttpStatus.BAD_REQUEST, "올바른 나이를 입력해주세요."), + INVALID_NAME(HttpStatus.BAD_REQUEST, "올바른 이름을 입력해주세요."), + DUPLICATED_NAME(HttpStatus.BAD_REQUEST, "이미 존재하는 이름입니다."), + NOT_FOUND_USER(HttpStatus.NOT_FOUND, "존재하지 않는 유저입니다."), + + //게시물 + NOT_FOUND_POST(HttpStatus.NOT_FOUND, "존재하지 않는 게시물입니다."), + NOT_MATCH_AUTHOR_MODIFIER(HttpStatus.BAD_REQUEST, "작성자와 수정자가 동일하지 않습니다."); + + private final HttpStatus status; + private final String message; + + ErrorCode(HttpStatus status, String message) { + this.status = status; + this.message = message; + } +} diff --git a/src/main/java/com/prgrms/boardjpa/global/config/JpaConfig.java b/src/main/java/com/prgrms/boardjpa/global/config/JpaConfig.java new file mode 100644 index 000000000..0f0d74471 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/global/config/JpaConfig.java @@ -0,0 +1,9 @@ +package com.prgrms.boardjpa.global.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@Configuration +@EnableJpaAuditing +public class JpaConfig { +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/global/domain/BaseEntity.java b/src/main/java/com/prgrms/boardjpa/global/domain/BaseEntity.java new file mode 100644 index 000000000..fc487b50e --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/global/domain/BaseEntity.java @@ -0,0 +1,24 @@ +package com.prgrms.boardjpa.global.domain; + +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.Column; +import javax.persistence.EntityListeners; +import javax.persistence.MappedSuperclass; +import java.time.LocalDateTime; + +@EntityListeners(AuditingEntityListener.class) +@Getter +@MappedSuperclass +public abstract class BaseEntity { + + @CreatedDate + @Column(updatable = false) + private LocalDateTime createdAt; + + @LastModifiedDate + private LocalDateTime updatedAt; +} diff --git a/src/main/java/com/prgrms/boardjpa/global/exception/BusinessServiceException.java b/src/main/java/com/prgrms/boardjpa/global/exception/BusinessServiceException.java new file mode 100644 index 000000000..2db91da50 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/global/exception/BusinessServiceException.java @@ -0,0 +1,14 @@ +package com.prgrms.boardjpa.global.exception; + +import com.prgrms.boardjpa.global.ErrorCode; +import lombok.Getter; + +@Getter +public class BusinessServiceException extends RuntimeException { + + private final ErrorCode errorCode; + + public BusinessServiceException(ErrorCode errorCode) { + this.errorCode = errorCode; + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/global/exception/GlobalExceptionHandler.java b/src/main/java/com/prgrms/boardjpa/global/exception/GlobalExceptionHandler.java new file mode 100644 index 000000000..f90e69688 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/global/exception/GlobalExceptionHandler.java @@ -0,0 +1,36 @@ +package com.prgrms.boardjpa.global.exception; + +import com.prgrms.boardjpa.global.response.ExceptionResponse; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(InvalidDomainConditionException.class) + public ResponseEntity domainException(InvalidDomainConditionException e) { + return ExceptionResponse.toResponseEntity(e.getErrorCode()); + } + + @ExceptionHandler(BusinessServiceException.class) + public ResponseEntity businessException(BusinessServiceException e) { + return ExceptionResponse.toResponseEntity(e.getErrorCode()); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity invalidMethodArgument(MethodArgumentNotValidException e) { + ExceptionResponse exceptionResponse = ExceptionResponse.builder() + .httpStatus(HttpStatus.BAD_REQUEST) + .message("잘못된 요청입니다.") + .build(); + + for (FieldError fieldError : e.getFieldErrors()) { + exceptionResponse.addValidation(fieldError.getField(), fieldError.getDefaultMessage()); + } + return new ResponseEntity<>(exceptionResponse, HttpStatus.BAD_REQUEST); + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/global/exception/InvalidDomainConditionException.java b/src/main/java/com/prgrms/boardjpa/global/exception/InvalidDomainConditionException.java new file mode 100644 index 000000000..589ee0657 --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/global/exception/InvalidDomainConditionException.java @@ -0,0 +1,14 @@ +package com.prgrms.boardjpa.global.exception; + +import com.prgrms.boardjpa.global.ErrorCode; +import lombok.Getter; + +@Getter +public class InvalidDomainConditionException extends RuntimeException { + + private final ErrorCode errorCode; + + public InvalidDomainConditionException(ErrorCode errorCode) { + this.errorCode = errorCode; + } +} \ No newline at end of file diff --git a/src/main/java/com/prgrms/boardjpa/global/response/ExceptionResponse.java b/src/main/java/com/prgrms/boardjpa/global/response/ExceptionResponse.java new file mode 100644 index 000000000..8914d6efe --- /dev/null +++ b/src/main/java/com/prgrms/boardjpa/global/response/ExceptionResponse.java @@ -0,0 +1,38 @@ +package com.prgrms.boardjpa.global.response; + +import com.prgrms.boardjpa.global.ErrorCode; +import lombok.Builder; +import lombok.Getter; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.util.HashMap; +import java.util.Map; + +@Getter +public class ExceptionResponse { + + private final HttpStatus httpStatus; + private final String message; + private final Map detailsMessage; + + @Builder + public ExceptionResponse(HttpStatus httpStatus, String message, Map detailsMessage) { + this.httpStatus = httpStatus; + this.message = message; + this.detailsMessage = detailsMessage != null ? detailsMessage : new HashMap<>(); + } + + public static ResponseEntity toResponseEntity(ErrorCode errorCode) { + return ResponseEntity + .status(errorCode.getStatus()) + .body(ExceptionResponse.builder() + .httpStatus(errorCode.getStatus()) + .message(errorCode.getMessage()) + .build()); + } + + public void addValidation(String filedName, String errorMessage) { + this.detailsMessage.put(filedName, errorMessage); + } +} \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 000000000..b45f2c25c --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,20 @@ +spring: + datasource: + url: jdbc:h2:tcp://localhost/~/board-jpa + username: sa + password: + driver-class-name: org.h2.Driver + jpa: + hibernate: + ddl-auto: create + properties: + hibernate: + # show_sql: true + format_sql: true + output: + ansi: + enabled: always + +logging.level: + org.hibernate.SQL: debug + # org.hibernate.type: trace diff --git a/src/main/resources/static/docs/index.html b/src/main/resources/static/docs/index.html new file mode 100644 index 000000000..957a36b74 --- /dev/null +++ b/src/main/resources/static/docs/index.html @@ -0,0 +1,1276 @@ + + + + + + + +REST Docs 게시판 API + + + + + + +
+
+

User API

+
+
+

유저 등록

+
+

/api/v1/users

+
+
Request
+
+
POST /api/v1/users HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Content-Length: 56
+Host: localhost:8080
+
+{
+  "name" : "lee",
+  "age" : 10,
+  "hobby" : "soccer"
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

name

String

name

age

Number

age

hobby

String

hobby

+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 68
+
+{
+  "id" : 2,
+  "name" : "lee",
+  "age" : 10,
+  "hobby" : "soccer"
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

id

Number

유저ID

name

String

이름

age

Number

나이

hobby

String

취미

+
+
Request Fail - 중복된 유저 이름
+
+
HTTP/1.1 400 Bad Request
+Content-Type: application/json
+Content-Length: 105
+
+{
+  "httpStatus" : "BAD_REQUEST",
+  "message" : "이미 존재하는 이름입니다.",
+  "valid" : { }
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

httpStatus

String

상태 코드

message

String

응답 메세지

valid

Object

상세 정보

+
+
Request Fail - 잘못된 데이터 입력
+
+
POST /api/v1/users HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Content-Length: 62
+Host: localhost:8080
+
+{
+  "name" : "@#@#@#(*&",
+  "age" : 10,
+  "hobby" : "soccer"
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

name

String

name

age

Number

age

hobby

String

hobby

+
+
+
HTTP/1.1 400 Bad Request
+Content-Type: application/json
+Content-Length: 155
+
+{
+  "httpStatus" : "BAD_REQUEST",
+  "message" : "잘못된 요청입니다.",
+  "valid" : {
+    "name" : "이름은 영어만 입력가능합니다."
+  }
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

httpStatus

String

상태 코드

message

String

응답 메세지

valid

Object

상세 정보

+
+
+
+
+
+

Post API

+
+
+

게시물 등록

+
+

/api/v1/posts

+
+
Request
+
+
POST /api/v1/posts HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Content-Length: 64
+Host: localhost:8080
+
+{
+  "userId" : 8,
+  "title" : "제목",
+  "content" : "내용"
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

userId

Number

User Id

title

String

Title

content

String

Content

+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 78
+
+{
+  "id" : 9,
+  "title" : "제목",
+  "content" : "내용",
+  "authorId" : 8
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

id

Number

게시판ID

title

String

제목

content

String

내용

authorId

Number

작성자ID

+
+
Request Fail - 존재하지 않는 유저
+
+
HTTP/1.1 404 Not Found
+Content-Type: application/json
+Content-Length: 103
+
+{
+  "httpStatus" : "NOT_FOUND",
+  "message" : "존재하지 않는 유저입니다.",
+  "valid" : { }
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

httpStatus

String

상태 코드

message

String

응답 메세지

valid

Object

상세 정보

+
+
Request Fail - 잘못된 데이터 입력
+
+
HTTP/1.1 400 Bad Request
+Content-Type: application/json
+Content-Length: 144
+
+{
+  "httpStatus" : "BAD_REQUEST",
+  "message" : "잘못된 요청입니다.",
+  "valid" : {
+    "title" : "제목을 입력해 주세요."
+  }
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

httpStatus

String

상태 코드

message

String

응답 메세지

valid

Object

상세 정보

+
+
+
+

게시물 전체 조회

+
+

/api/v1/posts

+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 212
+
+{
+  "postResponseList" : [ {
+    "id" : 3,
+    "title" : "제목",
+    "content" : "내용2",
+    "authorId" : 1
+  }, {
+    "id" : 2,
+    "title" : "제목1",
+    "content" : "내용1",
+    "authorId" : 1
+  } ]
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

postResponseList[].id

Number

Post Id

postResponseList[].title

String

Title

postResponseList[].content

String

Content

postResponseList[].authorId

Number

Author Id

+
+
+
+

게시물 단건 조회

+
+

/api/v1/posts/{id}

+
+
Request
+
+
GET /api/v1/posts/5 HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Host: localhost:8080
+
+
+ + ++++ + + + + + + + + + + + + +
Table 1. /api/v1/posts/{id}
ParameterDescription

id

Post Id

+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 80
+
+{
+  "id" : 5,
+  "title" : "제목1",
+  "content" : "내용1",
+  "authorId" : 4
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

id

Number

게시물ID

title

String

제목

content

String

내용

authorId

Number

작성자ID

+
+
Request Fail - 존재하지 않는 게시물
+
+
HTTP/1.1 404 Not Found
+Content-Type: application/json
+Content-Length: 106
+
+{
+  "httpStatus" : "NOT_FOUND",
+  "message" : "존재하지 않는 게시물입니다.",
+  "valid" : { }
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

httpStatus

String

상태 코드

message

String

응답 메세지

valid

Object

상세 정보

+
+
+
+

게시물 수정

+
+

/api/v1/posts/{id}

+
+
Request
+
+
PATCH /api/v1/posts/14 HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Content-Length: 60
+Host: localhost:8080
+
+{
+  "title" : "제목변경",
+  "content" : "내용변경"
+}
+
+
+ + ++++ + + + + + + + + + + + + +
Table 2. /api/v1/posts/{id}
ParameterDescription

id

Post Id

+ +++++ + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

title

String

Update Title

content

String

Update Content

+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 92
+
+{
+  "id" : 14,
+  "title" : "제목변경",
+  "content" : "내용변경",
+  "authorId" : 13
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

id

Number

수정된 게시물 ID

title

String

수정된 제목

content

String

수정된 내용

authorId

Number

작성자 ID

+
+
Request Fail - 존재하지 않는 게시물
+
+
HTTP/1.1 404 Not Found
+Content-Type: application/json
+Content-Length: 106
+
+{
+  "httpStatus" : "NOT_FOUND",
+  "message" : "존재하지 않는 게시물입니다.",
+  "valid" : { }
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

httpStatus

String

상태 코드

message

String

응답 메세지

valid

Object

상세 정보

+
+
+
+
+
+ + + + + + \ No newline at end of file diff --git a/src/test/java/com/prgrms/boardjpa/BoardJpaApplicationTests.java b/src/test/java/com/prgrms/boardjpa/BoardJpaApplicationTests.java new file mode 100644 index 000000000..75ea0f5fd --- /dev/null +++ b/src/test/java/com/prgrms/boardjpa/BoardJpaApplicationTests.java @@ -0,0 +1,13 @@ +package com.prgrms.boardjpa; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class BoardJpaApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/prgrms/boardjpa/Post/application/PostServiceTest.java b/src/test/java/com/prgrms/boardjpa/Post/application/PostServiceTest.java new file mode 100644 index 000000000..3bd01a046 --- /dev/null +++ b/src/test/java/com/prgrms/boardjpa/Post/application/PostServiceTest.java @@ -0,0 +1,157 @@ +package com.prgrms.boardjpa.Post.application; + +import com.prgrms.boardjpa.Post.domain.PostRepository; +import com.prgrms.boardjpa.Post.dto.request.PostCreateRequest; +import com.prgrms.boardjpa.Post.dto.request.PostUpdateRequest; +import com.prgrms.boardjpa.Post.dto.response.PostListResponse; +import com.prgrms.boardjpa.Post.dto.response.PostResponse; +import com.prgrms.boardjpa.User.domain.User; +import com.prgrms.boardjpa.User.domain.UserRepository; +import com.prgrms.boardjpa.global.exception.BusinessServiceException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.PageRequest; +import org.springframework.transaction.annotation.Transactional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@SpringBootTest +@Transactional +class PostServiceTest { + + @Autowired + PostService postService; + + @Autowired + PostRepository postRepository; + + @Autowired + UserRepository userRepository; + + PostCreateRequest postRequest; + + @BeforeEach + void setUp() { + User user = User.builder() + .name("hong") + .age(10) + .hobby("computer") + .build(); + User savedUser = userRepository.save(user); + + postRequest = PostCreateRequest.builder() + .title("제목") + .content("내용") + .userId(savedUser.getId()) + .build(); + } + + @Test + @DisplayName("Post생성 성공") + void createPostSuccessTest() throws Exception { + + //when + PostResponse postResponse = postService.create(postRequest); + + //then + assertThat(postResponse.title()).isEqualTo(postRequest.getTitle()); + assertThat(postResponse.content()).isEqualTo(postRequest.getContent()); + assertThat(postResponse.authorId()).isEqualTo(postRequest.getUserId()); + + } + + @Test + @DisplayName("Post 생성 실패 - 존재하지 않는 유저") + void createPostFailTest() throws Exception { + + //given + PostCreateRequest invalidRequest = PostCreateRequest.builder() + .title("제목") + .content("내용") + .userId(10L) + .build(); + + //when -> then + assertThrows(BusinessServiceException.class, + () -> postService.create(invalidRequest)); + } + + @Test + @DisplayName("게시물 단건 조회 성공") + void findPostByIdSuccessTest() throws Exception { + + //given + PostResponse postResponse = postService.create(postRequest); + + //when + PostResponse foundPost = postService.findOne(postResponse.id()); + + //then + assertThat(foundPost.title()).isEqualTo(postResponse.title()); + assertThat(foundPost.content()).isEqualTo(postResponse.content()); + } + + @Test + @DisplayName("게시물 단건 조회 실패 - 존재하지 않음") + void findPostByIdFailTest() throws Exception { + + //given + Long invalidId = 10L; + + //when -> then + assertThrows(BusinessServiceException.class, + () -> postService.findOne(invalidId)); + } + + @Test + @DisplayName("게시물 전체 조회") + void findAllPostsTest() throws Exception { + + //given + PostResponse postResponse = postService.create(postRequest); + PageRequest pageRequest = PageRequest.of(0, 5); + + //when + PostListResponse postListResponse = postService.findAll(pageRequest); + + //then + assertThat(postListResponse.postResponseList()).isNotNull(); + assertThat(postListResponse.postResponseList()).hasSize(1); + + PostResponse foundPost = postListResponse.postResponseList().get(0); + assertThat(foundPost.title()).isEqualTo(postResponse.title()); + } + + @Test + @DisplayName("게시물 업데이트 성공") + void updatePostSuccessTest() throws Exception { + + //given + PostResponse postResponse = postService.create(postRequest); + PostUpdateRequest postUpdateRequest = new PostUpdateRequest("제목변경", "내용변경"); + + //when + PostResponse updatedPost = postService.update(postResponse.id(), postUpdateRequest); + + //then + assertThat(updatedPost.title()).isEqualTo(postUpdateRequest.title()); + assertThat(updatedPost.content()).isEqualTo(postUpdateRequest.content()); + } + + @Test + @DisplayName("게시물 업데이트 실패 - 존재하지 않는 게시물") + void updatePostFailTest_post() throws Exception { + + //given + Long invalidPostId = 10L; + PostUpdateRequest postUpdateRequest = new PostUpdateRequest("제목변경", "내용변경"); + + //when -> then + assertThrows(BusinessServiceException.class, + () -> postService.update(invalidPostId, postUpdateRequest)); + } +} \ No newline at end of file diff --git a/src/test/java/com/prgrms/boardjpa/Post/presentation/PostApiControllerTest.java b/src/test/java/com/prgrms/boardjpa/Post/presentation/PostApiControllerTest.java new file mode 100644 index 000000000..77fc4c84f --- /dev/null +++ b/src/test/java/com/prgrms/boardjpa/Post/presentation/PostApiControllerTest.java @@ -0,0 +1,293 @@ +package com.prgrms.boardjpa.Post.presentation; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.prgrms.boardjpa.Post.application.PostService; +import com.prgrms.boardjpa.Post.dto.request.PostCreateRequest; +import com.prgrms.boardjpa.Post.dto.request.PostUpdateRequest; +import com.prgrms.boardjpa.Post.dto.response.PostListResponse; +import com.prgrms.boardjpa.Post.dto.response.PostResponse; +import com.prgrms.boardjpa.User.application.UserService; +import com.prgrms.boardjpa.global.ErrorCode; +import com.prgrms.boardjpa.global.exception.BusinessServiceException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; +import org.springframework.restdocs.operation.preprocess.Preprocessors; +import org.springframework.restdocs.snippet.Attributes; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.BDDMockito.given; +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; +import static org.springframework.restdocs.payload.JsonFieldType.*; +import static org.springframework.restdocs.payload.PayloadDocumentation.*; +import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; +import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@AutoConfigureRestDocs +@WebMvcTest(PostApiController.class) +class PostApiControllerTest { + + @Autowired + MockMvc mockMvc; + + @Autowired + ObjectMapper objectMapper; + + @MockBean + PostService postService; + + @MockBean + UserService userService; + + @Test + @DisplayName("게시물 등록 성공") + void createPostSuccessTest() throws Exception { + + //given + PostCreateRequest postCreateRequest = PostCreateRequest.builder() + .userId(1L) + .title("제목") + .content("내용") + .build(); + PostResponse postResponse = new PostResponse(1L, "제목", "내용", 1L); + + given(postService.create(any())) + .willReturn(postResponse); + + //when -> //then + mockMvc.perform(post("/api/v1/posts") + .contentType(APPLICATION_JSON) + .content(objectMapper.writeValueAsString(postCreateRequest))) + .andExpect(status().isOk()) + .andDo(print()) + .andDo(document("post-create", + Preprocessors.preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + requestFields( + fieldWithPath("userId").type(NUMBER).description("User Id"), + fieldWithPath("title").type(STRING).description("Title"), + fieldWithPath("content").type(STRING).description("Content")), + responseFields( + fieldWithPath("id").type(NUMBER).description("게시판ID"), + fieldWithPath("title").type(STRING).description("제목"), + fieldWithPath("content").type(STRING).description("내용"), + fieldWithPath("authorId").type(NUMBER).description("작성자ID")) + )); + } + + @Test + @DisplayName("게시물 등록 실패 - 존재하지 않는 유저") + void createPostFailTest_notFoundUser() throws Exception { + + //given + PostCreateRequest postCreateRequest = PostCreateRequest.builder() + .userId(30L) + .title("제목") + .content("내용") + .build(); + + given(postService.create(any())) + .willThrow(new BusinessServiceException(ErrorCode.NOT_FOUND_USER)); + + //when -> then + mockMvc.perform(post("/api/v1/posts") + .contentType(APPLICATION_JSON) + .content(objectMapper.writeValueAsString(postCreateRequest))) + .andExpect(status().isNotFound()) + .andDo(print()) + .andDo(document("post-create-fail-not-found-user", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + requestFields( + fieldWithPath("userId").type(NUMBER).description("User Id"), + fieldWithPath("title").type(STRING).description("Title"), + fieldWithPath("content").type(STRING).description("Content")), + responseFields( + fieldWithPath("httpStatus").type(STRING).description("상태 코드"), + fieldWithPath("message").type(STRING).description("응답 메세지"), + fieldWithPath("detailsMessage").type(OBJECT).description("상세 정보") + ))); + } + + @Test + @DisplayName("게시물 등록 실패 - 잘못된 데이터 입력") + void createPostFailTest_invalidData() throws Exception { + + //given + PostCreateRequest postCreateRequest = PostCreateRequest.builder() + .userId(30L) + .title(" ") + .content("내용") + .build(); + + //when -> then + mockMvc.perform(post("/api/v1/posts") + .contentType(APPLICATION_JSON) + .content(objectMapper.writeValueAsString(postCreateRequest))) + .andExpect(status().isBadRequest()) + .andDo(print()) + .andDo(document("post-create-fail-invalid-data", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + requestFields( + fieldWithPath("userId").type(NUMBER).description("User Id"), + fieldWithPath("title").type(STRING).description("Title"), + fieldWithPath("content").type(STRING).description("Content")), + responseFields( + fieldWithPath("httpStatus").type(STRING).description("상태 코드"), + fieldWithPath("message").type(STRING).description("응답 메세지"), + subsectionWithPath("detailsMessage").description("상세 정보") + .attributes( + Attributes.key("title").value("상세 에러 메세지 - 제목을 입력해 주세요.") + ) + ))); + } + + @Test + @DisplayName("게시물 전체 조회 성공") + void findAllSuccessTest() throws Exception { + + //given + PostListResponse response = new PostListResponse(List.of(new PostResponse(1L, "제목", "내용", 1L))); + given(postService.findAll(any())).willReturn(response); + + //when -> then + mockMvc.perform(get("/api/v1/posts") + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(print()) + .andDo(document("post-get-all", + preprocessResponse(prettyPrint()), + responseFields( + fieldWithPath("postResponseList[].id").type(NUMBER).description("Post Id"), + fieldWithPath("postResponseList[].title").type(STRING).description("Title"), + fieldWithPath("postResponseList[].content").type(STRING).description("Content"), + fieldWithPath("postResponseList[].authorId").type(NUMBER).description("Author Id") + ))); + } + + @Test + @DisplayName("게시물 단건 조회 성공") + void findOneSuccessTest() throws Exception { + + //given + PostResponse postResponse = new PostResponse(1L, "제목", "내용", 1L); + given(postService.findOne(anyLong())).willReturn(postResponse); + + //when -> then + mockMvc.perform(RestDocumentationRequestBuilders.get("/api/v1/posts/{id}", postResponse.id()) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(print()) + .andDo(document("post-get-one", + preprocessResponse(prettyPrint()), + pathParameters( + parameterWithName("id").description("Post Id")), + responseFields( + fieldWithPath("id").type(NUMBER).description("게시물ID"), + fieldWithPath("title").type(STRING).description("제목"), + fieldWithPath("content").type(STRING).description("내용"), + fieldWithPath("authorId").type(NUMBER).description("작성자ID") + ))); + } + + @Test + @DisplayName("게시물 단건 조회 실패 - 존재하지 않는 게시물") + void findOneFailTest_notFoundPost() throws Exception { + + long invalidId = 100L; + given(postService.findOne(any())).willThrow(new BusinessServiceException(ErrorCode.NOT_FOUND_POST)); + + //when -> then + mockMvc.perform(RestDocumentationRequestBuilders.get("/api/v1/posts/{id}", invalidId) + .contentType(APPLICATION_JSON)) + .andExpect(status().isNotFound()) + .andDo(print()) + .andDo(document("post-get-one-fail-not-found-post", + preprocessResponse(prettyPrint()), + pathParameters( + parameterWithName("id").description("Post Id")), + responseFields( + fieldWithPath("httpStatus").type(STRING).description("상태 코드"), + fieldWithPath("message").type(STRING).description("응답 메세지"), + fieldWithPath("detailsMessage").type(OBJECT).description("상세 정보") + ))); + } + + @Test + @DisplayName("게시물 수정 성공") + void updatePostSuccessTest() throws Exception { + + //given + PostUpdateRequest postUpdateRequest = new PostUpdateRequest("제목변경", "내용변경"); + PostResponse postResponse = new PostResponse(1L, "제목변경", "내용변경", 1L); + given(postService.update(anyLong(), any())).willReturn(postResponse); + + //when -> then + mockMvc.perform(RestDocumentationRequestBuilders.patch("/api/v1/posts/{id}", 1L) + .contentType(APPLICATION_JSON) + .content(objectMapper.writeValueAsString(postUpdateRequest))) + .andExpect(status().isOk()) + .andDo(print()) + .andDo(document("post-update", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + pathParameters( + parameterWithName("id").description("Post Id")), + requestFields( + fieldWithPath("title").type(STRING).description("Update Title"), + fieldWithPath("content").type(STRING).description("Update Content") + ), + responseFields( + fieldWithPath("id").type(NUMBER).description("수정된 게시물 ID"), + fieldWithPath("title").type(STRING).description("수정된 제목"), + fieldWithPath("content").type(STRING).description("수정된 내용"), + fieldWithPath("authorId").type(NUMBER).description("작성자 ID") + ))); + } + + @Test + @DisplayName("게시물 수정 실패 - 존재하지 않는 게시물") + void updatePostFailTest_notFoundPost() throws Exception { + + //given + PostUpdateRequest postUpdateRequest = new PostUpdateRequest("제목변경", "내용변경"); + + given(postService.update(anyLong(), any())).willThrow(new BusinessServiceException(ErrorCode.NOT_FOUND_POST)); + //when -> then + mockMvc.perform(RestDocumentationRequestBuilders.patch("/api/v1/posts/{id}", 100L) + .contentType(APPLICATION_JSON) + .content(objectMapper.writeValueAsString(postUpdateRequest))) + .andExpect(status().isNotFound()) + .andDo(print()) + .andDo(document("post-update-fail-not-found-post", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + pathParameters( + parameterWithName("id").description("Post Id")), + requestFields( + fieldWithPath("title").type(STRING).description("Update Title"), + fieldWithPath("content").type(STRING).description("Update Content") + ), + responseFields( + fieldWithPath("httpStatus").type(STRING).description("상태 코드"), + fieldWithPath("message").type(STRING).description("응답 메세지"), + fieldWithPath("detailsMessage").type(OBJECT).description("상세 정보") + ))); + } + +} \ No newline at end of file diff --git a/src/test/java/com/prgrms/boardjpa/User/application/UserServiceTest.java b/src/test/java/com/prgrms/boardjpa/User/application/UserServiceTest.java new file mode 100644 index 000000000..441ed2c83 --- /dev/null +++ b/src/test/java/com/prgrms/boardjpa/User/application/UserServiceTest.java @@ -0,0 +1,64 @@ +package com.prgrms.boardjpa.User.application; + +import com.prgrms.boardjpa.User.domain.UserRepository; +import com.prgrms.boardjpa.User.dto.UserRequest; +import com.prgrms.boardjpa.User.dto.UserResponse; +import com.prgrms.boardjpa.global.exception.BusinessServiceException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.transaction.annotation.Transactional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@SpringBootTest +@Transactional +class UserServiceTest { + + @Autowired + UserRepository userRepository; + + @Autowired + UserService userService; + + UserRequest userRequest; + + @BeforeEach + void setUp() { + userRequest = UserRequest.builder() + .name("hong") + .age(10) + .hobby("computer") + .build(); + } + + @Test + @DisplayName("유저 생성 성공") + void createUserSuccessTest() throws Exception { + + //when + UserResponse userResponse = userService.join(userRequest); + + //then + assertThat(userResponse.name()).isEqualTo(userRequest.getName()); + assertThat(userResponse.age()).isEqualTo(userRequest.getAge()); + } + + @Test + @DisplayName("유저 생성 실패 - 중복된 이름") + void createUserFailTest() throws Exception { + + UserRequest userRequest2 = UserRequest.builder() + .name("hong") + .age(20) + .hobby("soccer") + .build(); + UserResponse userResponse1 = userService.join(userRequest); + + //when -> //then + assertThrows(BusinessServiceException.class, () -> userService.join(userRequest2)); + } +} \ No newline at end of file diff --git a/src/test/java/com/prgrms/boardjpa/User/domain/UserTest.java b/src/test/java/com/prgrms/boardjpa/User/domain/UserTest.java new file mode 100644 index 000000000..9469a27d6 --- /dev/null +++ b/src/test/java/com/prgrms/boardjpa/User/domain/UserTest.java @@ -0,0 +1,39 @@ +package com.prgrms.boardjpa.User.domain; + +import com.prgrms.boardjpa.global.exception.InvalidDomainConditionException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +class UserTest { + + @ParameterizedTest + @ValueSource(ints = {-10, -1, -2}) + @DisplayName("유저 생성 실패 - 올바르지 않은 나이") + void creationFailTest_age(int invalidAge) throws Exception { + + //given -> when -> then + assertThrows(InvalidDomainConditionException.class, () -> User.builder() + .name("HONG") + .age(invalidAge) + .hobby("코딩") + .build()); + } + + @ParameterizedTest + @ValueSource(strings = {"", " "}) + @NullSource + @DisplayName("유저 생성 실패 - 올바르지 않은 이름") + void creationFailTest_name(String invalidName) throws Exception { + + //given -> when -> then + assertThrows(InvalidDomainConditionException.class, () -> User.builder() + .name(invalidName) + .age(10) + .hobby("코딩") + .build()); + } +} \ No newline at end of file diff --git a/src/test/java/com/prgrms/boardjpa/User/presentation/UserApiControllerTest.java b/src/test/java/com/prgrms/boardjpa/User/presentation/UserApiControllerTest.java new file mode 100644 index 000000000..4a2afe06a --- /dev/null +++ b/src/test/java/com/prgrms/boardjpa/User/presentation/UserApiControllerTest.java @@ -0,0 +1,144 @@ +package com.prgrms.boardjpa.User.presentation; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.prgrms.boardjpa.User.application.UserService; +import com.prgrms.boardjpa.User.dto.UserRequest; +import com.prgrms.boardjpa.User.dto.UserResponse; +import com.prgrms.boardjpa.global.ErrorCode; +import com.prgrms.boardjpa.global.exception.BusinessServiceException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.restdocs.payload.JsonFieldType; +import org.springframework.restdocs.snippet.Attributes; +import org.springframework.test.web.servlet.MockMvc; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; +import static org.springframework.restdocs.payload.JsonFieldType.OBJECT; +import static org.springframework.restdocs.payload.JsonFieldType.STRING; +import static org.springframework.restdocs.payload.PayloadDocumentation.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@AutoConfigureRestDocs +@WebMvcTest(UserApiController.class) +class UserApiControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @MockBean + private UserService userService; + + @Test + @DisplayName("유저 등록 성공") + void createUserSuccessTest() throws Exception { + + //given + UserRequest userRequest = UserRequest.builder() + .name("lee") + .age(10) + .hobby("soccer") + .build(); + UserResponse userResponse = new UserResponse(1L, "lee", 10, "soccer"); + given(userService.join(any())).willReturn(userResponse); + + //when -> then + mockMvc.perform(post("/api/v1/users") + .contentType(APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userRequest))) + .andExpect(status().isOk()) + .andDo(print()) + .andDo(document("user-join", + preprocessRequest(prettyPrint()), // 요청 포멧팅 + preprocessResponse(prettyPrint()), + requestFields( + fieldWithPath("name").type(JsonFieldType.STRING).description("name"), + fieldWithPath("age").type(JsonFieldType.NUMBER).description("age"), + fieldWithPath("hobby").type(JsonFieldType.STRING).description("hobby") + ), responseFields( + fieldWithPath("id").type(JsonFieldType.NUMBER).description("유저ID"), + fieldWithPath("name").type(JsonFieldType.STRING).description("이름"), + fieldWithPath("age").type(JsonFieldType.NUMBER).description("나이"), + fieldWithPath("hobby").type(JsonFieldType.STRING).description("취미") + ))); + } + + @Test + @DisplayName("유저 등록 실패 - 중복된 이름") + void createUserFailTest_duplicatedName() throws Exception { + + //given + UserRequest userRequest = UserRequest.builder() + .name("hong") + .age(10) + .hobby("soccer") + .build(); + given(userService.join(any())).willThrow(new BusinessServiceException(ErrorCode.DUPLICATED_NAME)); + + + //when -> then + mockMvc.perform(post("/api/v1/users") + .contentType(APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userRequest))) + .andExpect(status().isBadRequest()) + .andDo(print()) + .andDo(document("user-join-fail-duplicated-name", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + requestFields( + fieldWithPath("name").type(JsonFieldType.STRING).description("name"), + fieldWithPath("age").type(JsonFieldType.NUMBER).description("age"), + fieldWithPath("hobby").type(JsonFieldType.STRING).description("hobby") + ), responseFields( + fieldWithPath("httpStatus").type(STRING).description("상태 코드"), + fieldWithPath("message").type(STRING).description("응답 메세지"), + fieldWithPath("detailsMessage").type(OBJECT).description("상세 정보") + ))); + } + + @Test + @DisplayName("유저 등록 실패 - 잘못된 데이터 입력") + void createUserFailTest_invalidData() throws Exception { + + //given + UserRequest userRequest = UserRequest.builder() + .name("@#@#@#(*&") + .age(10) + .hobby("soccer") + .build(); + + //when -> then + mockMvc.perform(post("/api/v1/users") + .contentType(APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userRequest))) + .andExpect(status().isBadRequest()) + .andDo(print()) + .andDo(document("user-join-fail-invalid-data", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + requestFields( + fieldWithPath("name").type(JsonFieldType.STRING).description("name"), + fieldWithPath("age").type(JsonFieldType.NUMBER).description("age"), + fieldWithPath("hobby").type(JsonFieldType.STRING).description("hobby") + ), responseFields( + fieldWithPath("httpStatus").type(STRING).description("상태 코드"), + fieldWithPath("message").type(STRING).description("응답 메세지"), + subsectionWithPath("detailsMessage").description("상세 정보") + .attributes( + Attributes.key("name").value("상세 에러 메세지 - 이름은 영어만 가능합니다.") + ) + ))); + } +} \ No newline at end of file diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml new file mode 100644 index 000000000..e69de29bb