diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..b54929217 --- /dev/null +++ b/.gitignore @@ -0,0 +1,179 @@ +# Created by https://www.toptal.com/developers/gitignore/api/macos,intellij+all,java,gradle +# Edit at https://www.toptal.com/developers/gitignore?templates=macos,intellij+all,java,gradle + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+all Patch ### +# Ignore everything but code style settings and run configurations +# that are supposed to be shared within teams. + +.idea +.idea/* + +!.idea/codeStyles +!.idea/runConfigurations + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle Patch ### +# Java heap dump +*.hprof + +# End of https://www.toptal.com/developers/gitignore/api/macos,intellij+all,java,gradle \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..3f21a7c13 --- /dev/null +++ b/build.gradle @@ -0,0 +1,60 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.2' + id 'io.spring.dependency-management' version '1.1.2' + id 'org.asciidoctor.jvm.convert' version '3.3.2' +} + +group = 'com.example' +version = '1.0.0' + +java { + sourceCompatibility = '17' +} + +configurations { + asciidoctorExt + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + runtimeOnly 'com.h2database:h2' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + + asciidoctorExt 'org.springframework.restdocs:spring-restdocs-asciidoctor' + testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' +} + +ext { + set('snippetsDir', file("build/generated-snippets")) +} + +test { + outputs.dir snippetsDir + useJUnitPlatform() +} + +asciidoctor { + dependsOn test + inputs.dir snippetsDir + configurations 'asciidoctorExt' + baseDirFollowsSourceFile() +} + +bootJar { + dependsOn asciidoctor + from("${asciidoctor.outputDir}") { + into 'static/docs' + } +} 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..0795530c5 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'springboot-board-jpa' diff --git a/src/docs/asciidoc/index.adoc b/src/docs/asciidoc/index.adoc new file mode 100644 index 000000000..24eb82b4e --- /dev/null +++ b/src/docs/asciidoc/index.adoc @@ -0,0 +1,8 @@ += JPA Board - REST API Document +:doctype: book +:source-highlighter: highlightjs +:toc: left +:toclevels: 2 +:sectlinks: + +include::user.adoc[] diff --git a/src/docs/asciidoc/post.adoc b/src/docs/asciidoc/post.adoc new file mode 100644 index 000000000..dc40a6214 --- /dev/null +++ b/src/docs/asciidoc/post.adoc @@ -0,0 +1,21 @@ +== Post + +=== CREATE Post + +operation::post-controller-test/create-post-test[snippets='http-request,http-response'] + +=== READ Posts + +operation::post-controller-test/find-all-posts-test[snippets='http-request,http-response'] + +=== READ Post + +operation::post-controller-test/find-post-by-id-test[snippets='http-request,http-response'] + +=== UPDATE Post + +operation::post-controller-test/update-post-test[snippets='http-request,http-response'] + +=== DELETE Post + +operation::post-controller-test/delete-post-test[snippets='http-request,http-response'] diff --git a/src/docs/asciidoc/user.adoc b/src/docs/asciidoc/user.adoc new file mode 100644 index 000000000..812d4e51d --- /dev/null +++ b/src/docs/asciidoc/user.adoc @@ -0,0 +1,5 @@ +== User + +=== CREATE User + +operation::user-controller-test/create-user-test[snippets='http-request,http-response'] diff --git a/src/main/java/com/example/springbootboardjpa/SpringbootBoardJpaApplication.java b/src/main/java/com/example/springbootboardjpa/SpringbootBoardJpaApplication.java new file mode 100644 index 000000000..b2abbf69d --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/SpringbootBoardJpaApplication.java @@ -0,0 +1,15 @@ +package com.example.springbootboardjpa; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@EnableJpaAuditing +@SpringBootApplication +public class SpringbootBoardJpaApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootBoardJpaApplication.class, args); + } + +} diff --git a/src/main/java/com/example/springbootboardjpa/controller/PostController.java b/src/main/java/com/example/springbootboardjpa/controller/PostController.java new file mode 100644 index 000000000..1493a8842 --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/controller/PostController.java @@ -0,0 +1,46 @@ +package com.example.springbootboardjpa.controller; + +import com.example.springbootboardjpa.dto.post.request.PostCreateRequest; +import com.example.springbootboardjpa.dto.post.request.PostUpdateRequest; +import com.example.springbootboardjpa.dto.post.response.PostResponse; +import com.example.springbootboardjpa.service.PostService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/posts") +@RequiredArgsConstructor +public class PostController { + + private final PostService postService; + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public PostResponse createPost(@RequestBody PostCreateRequest createRequest) { + return postService.createPost(createRequest); + } + + @GetMapping + public List findPostAll() { + return postService.findAllPosts(); + } + + @GetMapping("/{id}") + public PostResponse findPostById(@PathVariable Long id) { + return postService.findPostById(id); + } + + @PatchMapping("/{id}") + public PostResponse updatePost(@PathVariable Long id, @RequestBody PostUpdateRequest updateRequest) { + return postService.updatePost(id, updateRequest); + } + + @DeleteMapping("/{id}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void deletePostById(@PathVariable Long id) { + postService.deletePostById(id); + } +} diff --git a/src/main/java/com/example/springbootboardjpa/controller/UserController.java b/src/main/java/com/example/springbootboardjpa/controller/UserController.java new file mode 100644 index 000000000..aa5b19f60 --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/controller/UserController.java @@ -0,0 +1,47 @@ +package com.example.springbootboardjpa.controller; + +import com.example.springbootboardjpa.dto.user.request.UserCreateRequest; +import com.example.springbootboardjpa.dto.user.request.UserUpdateRequest; +import com.example.springbootboardjpa.dto.user.response.UserRepsonse; +import com.example.springbootboardjpa.service.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/users") +@RequiredArgsConstructor +public class UserController { + + private final UserService userService; + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public UserRepsonse createUser(@RequestBody UserCreateRequest createRequest) { + return userService.createUser(createRequest); + } + + @GetMapping + public List findByUserAll() { + return userService.findAllUsers(); + } + + @GetMapping("/{id}") + public UserRepsonse findByUserById(@PathVariable Long id) { + return userService.findUserById(id); + } + + @PatchMapping("/{id}") + public UserRepsonse updateUser(@PathVariable Long id, @RequestBody UserUpdateRequest updateRequest) { + return userService.updateUser(id, updateRequest); + } + + + @DeleteMapping("/{id}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void deleteByUserById(@PathVariable Long id) { + userService.deleteCustomerById(id); + } +} diff --git a/src/main/java/com/example/springbootboardjpa/dto/post/request/PostCreateRequest.java b/src/main/java/com/example/springbootboardjpa/dto/post/request/PostCreateRequest.java new file mode 100644 index 000000000..6e52eb086 --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/dto/post/request/PostCreateRequest.java @@ -0,0 +1,23 @@ +package com.example.springbootboardjpa.dto.post.request; + +import com.example.springbootboardjpa.entity.Post; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class PostCreateRequest { + + private String title; + private String content; + private Long userId; + + public Post toEntity() { + return Post.builder() + .title(title) + .content(content) + .build(); + } +} diff --git a/src/main/java/com/example/springbootboardjpa/dto/post/request/PostUpdateRequest.java b/src/main/java/com/example/springbootboardjpa/dto/post/request/PostUpdateRequest.java new file mode 100644 index 000000000..ea2256a2e --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/dto/post/request/PostUpdateRequest.java @@ -0,0 +1,14 @@ +package com.example.springbootboardjpa.dto.post.request; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class PostUpdateRequest { + + private String title; + private String content; +} diff --git a/src/main/java/com/example/springbootboardjpa/dto/post/response/PostResponse.java b/src/main/java/com/example/springbootboardjpa/dto/post/response/PostResponse.java new file mode 100644 index 000000000..c84781225 --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/dto/post/response/PostResponse.java @@ -0,0 +1,42 @@ +package com.example.springbootboardjpa.dto.post.response; + +import com.example.springbootboardjpa.entity.Post; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Getter +@NoArgsConstructor +public class PostResponse { + + private Long postId; + private String title; + private String content; + private Long userId; + private LocalDateTime createdAt; + private String createdBy; + + + @Builder + private PostResponse(Long postId, String title, String content, Long userId, LocalDateTime createdAt, String createdBy) { + this.postId = postId; + this.title = title; + this.content = content; + this.userId = userId; + this.createdAt = createdAt; + this.createdBy = createdBy; + } + + public static PostResponse fromEntity(Post post) { + return PostResponse.builder() + .postId(post.getId()) + .title(post.getTitle()) + .content(post.getContent()) + .userId(post.getUser().getId()) + .createdAt(post.getCreatedAt()) + .createdBy(post.getCreatedBy()) + .build(); + } +} diff --git a/src/main/java/com/example/springbootboardjpa/dto/user/request/UserCreateRequest.java b/src/main/java/com/example/springbootboardjpa/dto/user/request/UserCreateRequest.java new file mode 100644 index 000000000..8053d5406 --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/dto/user/request/UserCreateRequest.java @@ -0,0 +1,24 @@ +package com.example.springbootboardjpa.dto.user.request; + +import com.example.springbootboardjpa.entity.User; +import com.example.springbootboardjpa.enums.Hobby; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class UserCreateRequest { + private String name; + private int age; + private Hobby hobby; + + public User toEntity() { + return User.builder() + .name(name) + .age(age) + .hobby(hobby) + .build(); + } +} diff --git a/src/main/java/com/example/springbootboardjpa/dto/user/request/UserUpdateRequest.java b/src/main/java/com/example/springbootboardjpa/dto/user/request/UserUpdateRequest.java new file mode 100644 index 000000000..dc7605e02 --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/dto/user/request/UserUpdateRequest.java @@ -0,0 +1,15 @@ +package com.example.springbootboardjpa.dto.user.request; + +import com.example.springbootboardjpa.enums.Hobby; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class UserUpdateRequest { + private String name; + private int age; + private Hobby hobby; +} diff --git a/src/main/java/com/example/springbootboardjpa/dto/user/response/UserRepsonse.java b/src/main/java/com/example/springbootboardjpa/dto/user/response/UserRepsonse.java new file mode 100644 index 000000000..92868c84d --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/dto/user/response/UserRepsonse.java @@ -0,0 +1,39 @@ +package com.example.springbootboardjpa.dto.user.response; + +import com.example.springbootboardjpa.entity.User; +import com.example.springbootboardjpa.enums.Hobby; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Getter +@NoArgsConstructor +public class UserRepsonse { + private Long userId; + private String name; + private int age; + private Hobby hobby; + private LocalDateTime createdAt; + private String createdBy; + + @Builder + public UserRepsonse(Long userId, String name, int age, Hobby hobby, LocalDateTime createdAt, String createdBy) { + this.userId = userId; + this.name = name; + this.age = age; + this.hobby = hobby; + this.createdAt = createdAt; + this.createdBy = createdBy; + } + + public static UserRepsonse fromEntity(User user) { + return UserRepsonse.builder() + .userId(user.getId()) + .name(user.getName()) + .age(user.getAge()) + .hobby(user.getHobby()) + .build(); + } +} diff --git a/src/main/java/com/example/springbootboardjpa/entity/BaseEntity.java b/src/main/java/com/example/springbootboardjpa/entity/BaseEntity.java new file mode 100644 index 000000000..2b70456bb --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/entity/BaseEntity.java @@ -0,0 +1,23 @@ +package com.example.springbootboardjpa.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@Getter +@EntityListeners(value = {AuditingEntityListener.class}) +@MappedSuperclass +public abstract class BaseEntity { + + @CreatedDate + @Column(name = "created_at", updatable = false) + protected LocalDateTime createdAt; + + @Column(name = "created_by", updatable = false) + protected String createdBy; +} diff --git a/src/main/java/com/example/springbootboardjpa/entity/Post.java b/src/main/java/com/example/springbootboardjpa/entity/Post.java new file mode 100644 index 000000000..1dc686022 --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/entity/Post.java @@ -0,0 +1,57 @@ +package com.example.springbootboardjpa.entity; + +import jakarta.persistence.*; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.Objects; + +@Entity +@Table(name = "post") +@NoArgsConstructor +@Getter +public class Post extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Column(name = "title", nullable = false, length = 100) + private String title; + + @Column(name = "content", nullable = false) + private String content; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(columnDefinition = "user_id", referencedColumnName = "id") + private User user; + + @Builder + private Post(String title, String content) { + this.title = title; + this.content = content; + } + + public void updateUser(User user) { + if (Objects.nonNull(this.user)) { + this.user.removePost(this); + } + this.user = user; + user.addPost(this); + setCreatedBy(user.getName()); + } + + + private void setCreatedBy(String name) { + this.createdBy = name; + } + + public void updateTitle(String title) { + this.title = title; + } + + public void updateContent(String content) { + this.content = content; + } +} diff --git a/src/main/java/com/example/springbootboardjpa/entity/User.java b/src/main/java/com/example/springbootboardjpa/entity/User.java new file mode 100644 index 000000000..322680ae8 --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/entity/User.java @@ -0,0 +1,61 @@ +package com.example.springbootboardjpa.entity; + +import com.example.springbootboardjpa.enums.Hobby; +import jakarta.persistence.*; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Table(name = "users") +@NoArgsConstructor +@Getter +public class User extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Column(name = "name", nullable = false, length = 30) + private String name; + + @Column(name = "age", nullable = false) + private int age; + + @Enumerated(EnumType.STRING) + private Hobby hobby; + + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) + private List posts = new ArrayList<>(); + + @Builder + private User(String name, int age, Hobby hobby) { + this.name = name; + this.age = age; + this.hobby = hobby; + } + + + public void updateName(String name) { + this.name = name; + } + + public void updateAge(int age) { + this.age = age; + } + + public void updateHobby(Hobby hobby) { + this.hobby = hobby; + } + + public void addPost(Post post) { + posts.add(post); + } + + public void removePost(Post post) { + posts.remove(post); + } +} diff --git a/src/main/java/com/example/springbootboardjpa/enums/Hobby.java b/src/main/java/com/example/springbootboardjpa/enums/Hobby.java new file mode 100644 index 000000000..b0a9f8bfa --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/enums/Hobby.java @@ -0,0 +1,15 @@ +package com.example.springbootboardjpa.enums; + +public enum Hobby { + EXERCISE("운동"), + GAME("게임"), + READING("독서"), + SINGING("노래"), + COOKING("요리"); + + private final String hobbyName; + + Hobby(String hobby) { + this.hobbyName = hobby; + } +} diff --git a/src/main/java/com/example/springbootboardjpa/repository/PostRepository.java b/src/main/java/com/example/springbootboardjpa/repository/PostRepository.java new file mode 100644 index 000000000..fdf2b1e2d --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/repository/PostRepository.java @@ -0,0 +1,7 @@ +package com.example.springbootboardjpa.repository; + +import com.example.springbootboardjpa.entity.Post; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PostRepository extends JpaRepository { +} diff --git a/src/main/java/com/example/springbootboardjpa/repository/UserRepository.java b/src/main/java/com/example/springbootboardjpa/repository/UserRepository.java new file mode 100644 index 000000000..f27497ef5 --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/repository/UserRepository.java @@ -0,0 +1,7 @@ +package com.example.springbootboardjpa.repository; + +import com.example.springbootboardjpa.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} diff --git a/src/main/java/com/example/springbootboardjpa/service/PostService.java b/src/main/java/com/example/springbootboardjpa/service/PostService.java new file mode 100644 index 000000000..e44103e67 --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/service/PostService.java @@ -0,0 +1,68 @@ +package com.example.springbootboardjpa.service; + +import com.example.springbootboardjpa.dto.post.request.PostCreateRequest; +import com.example.springbootboardjpa.dto.post.request.PostUpdateRequest; +import com.example.springbootboardjpa.dto.post.response.PostResponse; +import com.example.springbootboardjpa.entity.Post; +import com.example.springbootboardjpa.entity.User; +import com.example.springbootboardjpa.repository.PostRepository; +import com.example.springbootboardjpa.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.NoSuchElementException; + +@Service +@RequiredArgsConstructor +public class PostService { + + private final UserRepository userRepository; + private final PostRepository postRepository; + + @Transactional + public PostResponse createPost(PostCreateRequest postCreateRequest) { + User user = userRepository.findById(postCreateRequest.getUserId()) + .orElseThrow(() -> new NoSuchElementException("해당 유저가 존재하지 않습니다.")); + + + Post post = postCreateRequest.toEntity(); + post.updateUser(user); + postRepository.save(post); + return PostResponse.fromEntity(post); + } + + public List findAllPosts() { + return postRepository.findAll() + .stream() + .map(PostResponse::fromEntity) + .toList(); + } + + public PostResponse findPostById(Long id) { + Post post = postRepository.findById(id) + .orElseThrow(() -> new NoSuchElementException("해당 게시글은 존재하지 않습니다.")); + return PostResponse.fromEntity(post); + } + + @Transactional + public PostResponse updatePost(Long id, PostUpdateRequest updateRequest) { + Post post = postRepository.findById(id) + .orElseThrow(() -> new NoSuchElementException("수정하려는 게시글이 존재하지 않습니다.")); + + post.updateTitle(updateRequest.getTitle()); + post.updateContent(updateRequest.getContent()); + + return PostResponse.fromEntity(post); + } + + @Transactional + public void deletePostById(Long id) { + if (!postRepository.existsById(id)) { + throw new NoSuchElementException("삭제하려는 게시글을 찾지 못했습니다."); + } + + postRepository.deleteById(id); + } +} diff --git a/src/main/java/com/example/springbootboardjpa/service/UserService.java b/src/main/java/com/example/springbootboardjpa/service/UserService.java new file mode 100644 index 000000000..c28938f7d --- /dev/null +++ b/src/main/java/com/example/springbootboardjpa/service/UserService.java @@ -0,0 +1,62 @@ +package com.example.springbootboardjpa.service; + +import com.example.springbootboardjpa.dto.user.request.UserCreateRequest; +import com.example.springbootboardjpa.dto.user.request.UserUpdateRequest; +import com.example.springbootboardjpa.dto.user.response.UserRepsonse; +import com.example.springbootboardjpa.entity.User; +import com.example.springbootboardjpa.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.NoSuchElementException; + +@Service +@RequiredArgsConstructor +public class UserService { + + private final UserRepository userRepository; + + @Transactional + public UserRepsonse createUser(UserCreateRequest userCreateRequest) { + User user = userRepository.save(userCreateRequest.toEntity()); + return UserRepsonse.fromEntity(user); + } + + public List findAllUsers() { + return userRepository.findAll() + .stream() + .map(UserRepsonse::fromEntity) + .toList(); + } + + public UserRepsonse findUserById(Long id) { + User user = userRepository.findById(id) + .orElseThrow(() -> new NoSuchElementException("해당 회원은 존재하지 않습니다. ")); + + return UserRepsonse.fromEntity(user); + } + + @Transactional + public UserRepsonse updateUser(Long id, UserUpdateRequest updateRequest) { + User user = userRepository.findById(id) + .orElseThrow(() -> new NoSuchElementException("수정하려는 회원이 존재하지 않습니다.")); + + user.updateName(updateRequest.getName()); + user.updateAge(updateRequest.getAge()); + user.updateHobby(updateRequest.getHobby()); + + return UserRepsonse.fromEntity(user); + } + + + @Transactional + public void deleteCustomerById(Long id) { + if (!userRepository.existsById(id)) { + throw new NoSuchElementException("삭제하려는 회원을 찾지 못했습니다."); + } + + userRepository.deleteById(id); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 000000000..1501fa874 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,22 @@ +spring: + datasource: + driver-class-name: org.h2.Driver + url: jdbc:h2:mem:/test + username: sa + password: + jpa: + hibernate: + ddl-auto: update + database-platform: org.hibernate.dialect.H2Dialect + properties: + hibernate: + format_sql: true + +logging: + level: + org: + hibernate: + SQL: debug + type: + descriptor: + sql: trace \ No newline at end of file diff --git a/src/test/java/com/example/springbootboardjpa/RestDocs/AbstractRestDocesTest.java b/src/test/java/com/example/springbootboardjpa/RestDocs/AbstractRestDocesTest.java new file mode 100644 index 000000000..8030c155f --- /dev/null +++ b/src/test/java/com/example/springbootboardjpa/RestDocs/AbstractRestDocesTest.java @@ -0,0 +1,37 @@ +package com.example.springbootboardjpa.RestDocs; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.context.annotation.Import; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; +import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.filter.CharacterEncodingFilter; + +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; + +@Import(RestDocsConfiguration.class) +@ExtendWith(RestDocumentationExtension.class) +public class AbstractRestDocesTest { + protected RestDocumentationResultHandler resultHandler; + protected MockMvc mockMvc; + + protected AbstractRestDocesTest(RestDocumentationResultHandler resultHandler, MockMvc mockMvc) { + this.resultHandler = resultHandler; + this.mockMvc = mockMvc; + } + + @BeforeEach + void setUp(final WebApplicationContext context, final RestDocumentationContextProvider provider) { + this.mockMvc = MockMvcBuilders.webAppContextSetup(context) + .apply(documentationConfiguration(provider)) + .alwaysDo(print()) + .alwaysDo(resultHandler) + .addFilters(new CharacterEncodingFilter("UTF-8", true)) + .build(); + } +} diff --git a/src/test/java/com/example/springbootboardjpa/RestDocs/RestDocsConfiguration.java b/src/test/java/com/example/springbootboardjpa/RestDocs/RestDocsConfiguration.java new file mode 100644 index 000000000..224cf8e37 --- /dev/null +++ b/src/test/java/com/example/springbootboardjpa/RestDocs/RestDocsConfiguration.java @@ -0,0 +1,20 @@ +package com.example.springbootboardjpa.RestDocs; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; +import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; +import org.springframework.restdocs.operation.preprocess.Preprocessors; + +@Configuration +public class RestDocsConfiguration { + + @Bean + public RestDocumentationResultHandler write() { + return MockMvcRestDocumentation.document( + "{class-name}/{method-name}", + Preprocessors.preprocessRequest(Preprocessors.prettyPrint()), + Preprocessors.preprocessResponse(Preprocessors.prettyPrint()) + ); + } +} diff --git a/src/test/java/com/example/springbootboardjpa/SpringbootBoardJpaApplicationTests.java b/src/test/java/com/example/springbootboardjpa/SpringbootBoardJpaApplicationTests.java new file mode 100644 index 000000000..d1acee266 --- /dev/null +++ b/src/test/java/com/example/springbootboardjpa/SpringbootBoardJpaApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.springbootboardjpa; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootBoardJpaApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/example/springbootboardjpa/controller/PostControllerTest.java b/src/test/java/com/example/springbootboardjpa/controller/PostControllerTest.java new file mode 100644 index 000000000..75df5861e --- /dev/null +++ b/src/test/java/com/example/springbootboardjpa/controller/PostControllerTest.java @@ -0,0 +1,176 @@ +package com.example.springbootboardjpa.controller; + +import com.example.springbootboardjpa.RestDocs.AbstractRestDocesTest; +import com.example.springbootboardjpa.dto.post.request.PostCreateRequest; +import com.example.springbootboardjpa.dto.post.request.PostUpdateRequest; +import com.example.springbootboardjpa.dto.user.request.UserCreateRequest; +import com.example.springbootboardjpa.service.PostService; +import com.example.springbootboardjpa.service.UserService; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestInstance.Lifecycle; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; +import org.springframework.restdocs.payload.JsonFieldType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import static com.example.springbootboardjpa.enums.Hobby.GAME; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; +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.result.MockMvcResultMatchers.status; + +@AutoConfigureMockMvc +@SpringBootTest +@TestInstance(Lifecycle.PER_CLASS) +class PostControllerTest extends AbstractRestDocesTest { + + private final ObjectMapper objectMapper; + private final PostService postService; + private final UserService userService; + + @Autowired + public PostControllerTest(RestDocumentationResultHandler resultHandler, MockMvc mockMvc, ObjectMapper objectMapper, + UserService userService, PostService postService) { + super(resultHandler, mockMvc); + this.objectMapper = objectMapper; + this.postService = postService; + this.userService = userService; + } + + @BeforeAll() + void savePostandUser() { + UserCreateRequest userCreateRequest = new UserCreateRequest("Kim Jae won", 28, GAME); + userService.createUser(userCreateRequest); + + PostCreateRequest postCreateRequest1 = new PostCreateRequest("kim jae won", "타일러 팀원의 멘토님은 kim jae won입니다!!", 1L); + PostCreateRequest postCreateRequest2 = new PostCreateRequest("so jae hoon", "타일러 팀원은 최고입니다!!!", 1L); + postService.createPost(postCreateRequest1); + postService.createPost(postCreateRequest2); + } + + @Test + @DisplayName("[REST DOCS] CREATE Post") + @Transactional + void createPostTest() throws Exception { + PostCreateRequest request = new PostCreateRequest("황창현", "황창현은 바부입니다!", 1L); + + mockMvc.perform(post("/api/posts") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isCreated()) + .andDo(resultHandler.document( + requestFields( + fieldWithPath("title").type(JsonFieldType.STRING).description("게시물 제목"), + fieldWithPath("content").type(JsonFieldType.STRING).description("게시물 내용"), + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("유저 ID") + ), + responseFields( + fieldWithPath("postId").type(JsonFieldType.NUMBER).description("게시물 ID"), + fieldWithPath("title").type(JsonFieldType.STRING).description("게시물 제목"), + fieldWithPath("content").type(JsonFieldType.STRING).description("게시물 내용"), + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("작성자 ID"), + fieldWithPath("createdAt").type(JsonFieldType.STRING).description("게시물 작성 일자"), + fieldWithPath("createdBy").type(JsonFieldType.STRING).description("게시물 작성자") + ) + )); + + } + + @Test + @DisplayName("[REST DOCS] GET All posts") + void findByUserAllTest() throws Exception { + mockMvc.perform(get("/api/posts") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(resultHandler.document( + responseFields( + fieldWithPath("[]postId").type(JsonFieldType.NUMBER).description("게시물 ID"), + fieldWithPath("[]title").type(JsonFieldType.STRING).description("게시물 제목"), + fieldWithPath("[]content").type(JsonFieldType.STRING).description("게시물 내용"), + fieldWithPath("[]userId").type(JsonFieldType.NUMBER).description("작성자 ID"), + fieldWithPath("[]createdAt").type(JsonFieldType.STRING).description("게시물 작성일시"), + fieldWithPath("[]createdBy").type(JsonFieldType.STRING).description("게시물 작성자") + ) + )); + } + + @Test + @DisplayName("[REST DOCS] GET post by ID") + void findByUserByIdTest() throws Exception { + long postId = 1; + + mockMvc.perform(get("/api/posts/{id}", postId) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(resultHandler.document( + pathParameters( + parameterWithName("id").description("조회할 게시물 ID") + ), + responseFields( + fieldWithPath("postId").type(JsonFieldType.NUMBER).description("게시물 ID"), + fieldWithPath("title").type(JsonFieldType.STRING).description("게시물 제목"), + fieldWithPath("content").type(JsonFieldType.STRING).description("게시물 내용"), + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("작성자 ID"), + fieldWithPath("createdAt").type(JsonFieldType.STRING).description("게시물 작성일시"), + fieldWithPath("createdBy").type(JsonFieldType.STRING).description("게시물 작성자") + ) + )); + } + + @Test + @DisplayName("[REST DOCS] UPDATE user") + @Transactional + void updatePostTest() throws Exception { + long postId = 1L; + PostUpdateRequest request = new PostUpdateRequest("황창현 바부", "황창현은 엄청난 바부입니다."); + + mockMvc.perform(patch("/api/posts/{id}", postId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(resultHandler.document( + pathParameters( + parameterWithName("id").description("수정할 게시물 ID") + ), + requestFields( + fieldWithPath("title").type(JsonFieldType.STRING).description("수정할 게시물 제목"), + fieldWithPath("content").type(JsonFieldType.STRING).description("수정할 게시물 내용") + ), + responseFields( + fieldWithPath("postId").type(JsonFieldType.NUMBER).description("게시물 ID"), + fieldWithPath("title").type(JsonFieldType.STRING).description("게시물 제목"), + fieldWithPath("content").type(JsonFieldType.STRING).description("게시물 내용"), + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("작성자 ID"), + fieldWithPath("createdAt").type(JsonFieldType.STRING).description("게시물 작성 일자"), + fieldWithPath("createdBy").type(JsonFieldType.STRING).description("게시물 작성자") + ) + )); + } + + @Test + @DisplayName("[REST DOCS] DELETE post by ID") + @Transactional + void deleteByPostByIdTest() throws Exception { + long postId = 1; + + mockMvc.perform(delete("/api/posts/{id}", postId) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()) + .andDo(resultHandler.document( + pathParameters( + parameterWithName("id").description("삭제할 게시물 ID") + ) + )); + } +} diff --git a/src/test/java/com/example/springbootboardjpa/controller/UserControllerTest.java b/src/test/java/com/example/springbootboardjpa/controller/UserControllerTest.java new file mode 100644 index 000000000..3ef32b704 --- /dev/null +++ b/src/test/java/com/example/springbootboardjpa/controller/UserControllerTest.java @@ -0,0 +1,169 @@ +package com.example.springbootboardjpa.controller; + +import com.example.springbootboardjpa.RestDocs.AbstractRestDocesTest; +import com.example.springbootboardjpa.dto.user.request.UserCreateRequest; +import com.example.springbootboardjpa.service.UserService; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestInstance.Lifecycle; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; +import org.springframework.restdocs.payload.JsonFieldType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import static com.example.springbootboardjpa.enums.Hobby.GAME; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; +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.result.MockMvcResultMatchers.status; + +@AutoConfigureMockMvc +@SpringBootTest +@TestInstance(Lifecycle.PER_CLASS) +class UserControllerTest extends AbstractRestDocesTest { + + private final ObjectMapper objectMapper; + private final UserService userService; + + @Autowired + public UserControllerTest(RestDocumentationResultHandler resultHandler, MockMvc mockMvc, ObjectMapper objectMapper, + UserService userService) { + super(resultHandler, mockMvc); + this.objectMapper = objectMapper; + this.userService = userService; + } + + @BeforeEach + void saveUser() { + UserCreateRequest request = new UserCreateRequest("Kim Jae won", 28, GAME); + userService.createUser(request); + } + + @Test + @DisplayName("[REST DOCS] CREATE User") + @Transactional + void createUserTest() throws Exception { + UserCreateRequest request = new UserCreateRequest("Kim Jae won", 28, GAME); + + mockMvc.perform(post("/api/users") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isCreated()) + .andDo(resultHandler.document( + requestFields( + fieldWithPath("name").type(JsonFieldType.STRING).description("이름"), + fieldWithPath("age").type(JsonFieldType.NUMBER).description("나이"), + fieldWithPath("hobby").type(JsonFieldType.STRING).description("취미") + ), + responseFields( + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("사용자 ID"), + fieldWithPath("name").type(JsonFieldType.STRING).description("이름"), + fieldWithPath("age").type(JsonFieldType.NUMBER).description("나이"), + fieldWithPath("hobby").type(JsonFieldType.STRING).description("취미"), + fieldWithPath("createdAt").type(JsonFieldType.STRING).description("생성 일자").optional(), + fieldWithPath("createdBy").type(JsonFieldType.STRING).description("생성자").optional() + ) + )); + } + + @Test + @DisplayName("[REST DOCS] GET All Users") + void findByUserAllTest() throws Exception { + mockMvc.perform(get("/api/users") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(resultHandler.document( + responseFields( + fieldWithPath("[].userId").type(JsonFieldType.NUMBER).description("사용자 ID"), + fieldWithPath("[].name").type(JsonFieldType.STRING).description("이름"), + fieldWithPath("[].age").type(JsonFieldType.NUMBER).description("나이"), + fieldWithPath("[].hobby").type(JsonFieldType.STRING).description("취미"), + fieldWithPath("[].createdAt").type(JsonFieldType.STRING).description("생성 일시").optional(), + fieldWithPath("[].createdBy").type(JsonFieldType.STRING).description("생성자").optional() + ) + )); + + } + + @Test + @DisplayName("[REST DOCS] GET user by ID") + void findByUserByIdTest() throws Exception { + long userId = 1; + + mockMvc.perform(get("/api/users/{id}", userId) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(resultHandler.document( + pathParameters( + parameterWithName("id").description("사용자 ID") + ), + responseFields( + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("사용자 ID"), + fieldWithPath("name").type(JsonFieldType.STRING).description("이름"), + fieldWithPath("age").type(JsonFieldType.NUMBER).description("나이"), + fieldWithPath("hobby").type(JsonFieldType.STRING).description("취미"), + fieldWithPath("createdAt").type(JsonFieldType.STRING).description("생성 일시").optional(), + fieldWithPath("createdBy").type(JsonFieldType.STRING).description("생성자").optional() + ) + )); + + } + + @Test + @DisplayName("[REST DOCS] UPDATE user") + @Transactional + void updateUserTest() throws Exception { + long userId = 1; + UserCreateRequest request = new UserCreateRequest("Kim Jae won", 28, GAME); + + + mockMvc.perform(patch("/api/users/{id}", userId) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(resultHandler.document( + pathParameters( + parameterWithName("id").description("사용자 ID") + ), + requestFields( + fieldWithPath("name").type(JsonFieldType.STRING).description("이름"), + fieldWithPath("age").type(JsonFieldType.NUMBER).description("나이"), + fieldWithPath("hobby").type(JsonFieldType.STRING).description("취미") + ), + responseFields( + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("사용자 ID"), + fieldWithPath("name").type(JsonFieldType.STRING).description("이름"), + fieldWithPath("age").type(JsonFieldType.NUMBER).description("나이"), + fieldWithPath("hobby").type(JsonFieldType.STRING).description("취미"), + fieldWithPath("createdAt").type(JsonFieldType.STRING).description("생성 일시").optional(), + fieldWithPath("createdBy").type(JsonFieldType.STRING).description("생성자").optional() + ) + )); + } + + @Test + @DisplayName("[REST DOCS] DELETE user by ID") + @Transactional + void deleteByUserByIdTest() throws Exception { + long userId = 1; + + mockMvc.perform(delete("/api/users/{id}", userId) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()) + .andDo(resultHandler.document( + pathParameters( + parameterWithName("id").description("사용자 ID") + ) + )); + } +}