diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..9c5e52c27 --- /dev/null +++ b/.gitignore @@ -0,0 +1,226 @@ +# Created by https://www.toptal.com/developers/gitignore/api/gradle,java,macos,windows,visualstudiocode,intellij+all +# Edit at https://www.toptal.com/developers/gitignore?templates=gradle,java,macos,windows,visualstudiocode,intellij+all + +### 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/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 + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### 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/gradle,java,macos,windows,visualstudiocode,intellij+all + +.idea/ +HELP.md \ No newline at end of file diff --git a/HELP.md b/HELP.md new file mode 100644 index 000000000..1f960cf95 --- /dev/null +++ b/HELP.md @@ -0,0 +1,28 @@ +# Getting Started + +### Reference Documentation + +For further reference, please consider the following sections: + +* [Official Gradle documentation](https://docs.gradle.org) +* [Spring Boot Gradle Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/3.1.5/gradle-plugin/reference/html/) +* [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.1.5/gradle-plugin/reference/html/#build-image) +* [Spring Web](https://docs.spring.io/spring-boot/docs/3.1.5/reference/htmlsingle/index.html#web) +* [Spring Data JPA](https://docs.spring.io/spring-boot/docs/3.1.5/reference/htmlsingle/index.html#data.sql.jpa-and-spring-data) + +### Guides + +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) +* [Accessing data with MySQL](https://spring.io/guides/gs/accessing-data-mysql/) +* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) + +### Additional Links + +These additional references should also help you: + +* [Gradle Build Scans – insights for your project's build](https://scans.gradle.com#gradle) + diff --git a/README.md b/README.md index cb154de0f..94a596782 100644 --- a/README.md +++ b/README.md @@ -12,4 +12,4 @@ Spring Boot JPA - Rest API를 강의를 듣고, 게시판 구현 미션을 수 ## Branch 명명 규칙 1. 여러분 repo는 알아서 해주시고 😀(본인 레포니 main으로 하셔두 되져) 2. prgrms-be-devcourse/spring-board 레포로 PR시 branch는 본인 username을 적어주세요 :) -base repo : `여기repo` base : `username` ← head repo : `여러분repo` compare : `main` +base repo : `여기repo` base : `username` ← head repo : `여러분repo` compare : `main` \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..4b8a44950 --- /dev/null +++ b/build.gradle @@ -0,0 +1,62 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.5' + id 'io.spring.dependency-management' version '1.1.3' + id "org.asciidoctor.jvm.convert" version "3.3.2" +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } + asciidoctorExt +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + implementation 'org.springframework.boot:spring-boot-starter-validation' + + // ascii-docs + asciidoctorExt 'org.springframework.restdocs:spring-restdocs-asciidoctor' + testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' + + // redis + implementation 'org.springframework.boot:spring-boot-starter-data-redis' + +} + +ext { + snippetsDir = file('build/generated-snippets') + asciidocDir = file('src/docs/asciidoc') +} + +tasks.named('bootBuildImage') { + builder = 'paketobuildpacks/builder-jammy-base:latest' +} + +tasks.named('test') { + useJUnitPlatform() +} + +asciidoctor { + inputs.dir snippetsDir + configurations 'asciidoctorExt' + dependsOn test + outputs.dir asciidocDir // 추가된 부분 +} \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..dbf0782ac --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,22 @@ +version: "3.8" + +services: + mysql: + build: + context: ./mysql + dockerfile: Dockerfile + ports: + - "3308:3306" + volumes: + - "data_volume:/var/lib/mysql" + environment: + MYSQL_PASSWORD: "root" + MYSQL_ROOT_PASSWORD: "root" + MYSQL_DATABASE: "board" + redis: + image: "redis:latest" + ports: + - "6830:6379" + +volumes: + data_volume: \ 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..7f93135c4 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..3fa8f862f --- /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.4-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..1aa94a426 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/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##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && 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=SC2039,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=SC2039,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, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +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/mysql/01_schema.sql b/mysql/01_schema.sql new file mode 100644 index 000000000..5034d76d1 --- /dev/null +++ b/mysql/01_schema.sql @@ -0,0 +1,53 @@ +CREATE DATABASE IF NOT EXISTS board; + +USE board; + +create table users +( + user_id bigint primary key auto_increment, + name varchar(20) not null , + age int not null, + hobby varchar(20) not null , + created_at datetime not null , + updated_at datetime not null +); + +create table posts +( + post_id bigint primary key auto_increment, + user_id bigint not null , + title varchar(30) not null, + contents blob not null , + created_at datetime not null , + updated_at datetime not null, + created_by varchar(20) not null, + + constraint post_user_fk FOREIGN key (user_id) references users(user_id) +); + +CREATE DATABASE IF NOT EXISTS board_test; + +USE board_test; + +create table users +( + user_id bigint primary key auto_increment, + name varchar(20) not null , + age int not null, + hobby varchar(20) not null , + created_at datetime not null , + updated_at datetime not null +); + +create table posts +( + post_id bigint primary key auto_increment, + user_id bigint not null , + title varchar(30) not null, + contents blob not null , + created_at datetime not null , + updated_at datetime not null, + created_by varchar(20) not null, + + constraint post_user_fk FOREIGN key (user_id) references users(user_id) +); \ No newline at end of file diff --git a/mysql/02_data.sql b/mysql/02_data.sql new file mode 100644 index 000000000..945c31ab7 --- /dev/null +++ b/mysql/02_data.sql @@ -0,0 +1,5 @@ +USE board; +insert into users (name, age, hobby, created_at, updated_at) values ('test', 20, 'coding', now(), now()); + +USE board_test; +insert into users (name, age, hobby, created_at, updated_at) values ('test', 20, 'coding', now(), now()); \ No newline at end of file diff --git a/mysql/Dockerfile b/mysql/Dockerfile new file mode 100644 index 000000000..d20d95749 --- /dev/null +++ b/mysql/Dockerfile @@ -0,0 +1,6 @@ +# Use the official MySQL 8 image as the base image +FROM mysql:8 +ENV MYSQL_ROOT_PASSWORD=root +ENV MYSQL_DATABASE=board +ENV MYSQL_ROOT_USER=root +COPY ./ /docker-entrypoint-initdb.d/ \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..5f717a7cc --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'board' diff --git a/src/.DS_Store b/src/.DS_Store new file mode 100644 index 000000000..f0b988e0d Binary files /dev/null and b/src/.DS_Store differ diff --git a/src/docs/asciidoc/index.adoc b/src/docs/asciidoc/index.adoc new file mode 100644 index 000000000..e6dc022a1 --- /dev/null +++ b/src/docs/asciidoc/index.adoc @@ -0,0 +1,81 @@ +:hardbreaks: +ifndef::snippets[] +:snippets: ../../../build/generated-snippets +endif::[] + +== 게시글 +=== 게시글 등록 +==== /api/v1/posts + +.Request + +include::{snippets}/post-save/http-request.adoc[] + +.Request Fields + +include::{snippets}/post-save/request-fields.adoc[] + +.Response + +include::{snippets}/post-save/http-response.adoc[] + +.Response Fields + +include::{snippets}/post-save/response-fields.adoc[] + +=== 게시글 전체조회 +==== /api/v1/posts + +.Request + +include::{snippets}/post-getAll/http-request.adoc[] + +.Request Fields + +include::{snippets}/post-getAll/request-fields.adoc[] + +.Response + +include::{snippets}/post-getAll/http-response.adoc[] + +.Response Fields + +include::{snippets}/post-getAll/response-fields.adoc[] + +=== 게시글 단건 조회 +==== /api/v1/posts/{postId} + +.Request + +include::{snippets}/post-getById/http-request.adoc[] + +.Request Fields + +include::{snippets}/post-getById/request-fields.adoc[] + +.Response + +include::{snippets}/post-getById/http-response.adoc[] + +.Response Fields + +include::{snippets}/post-getById/response-fields.adoc[] + +=== 게시글 수정 +==== /api/v1/posts/{postId} + +.Request + +include::{snippets}/post-update/http-request.adoc[] + +.Request Fields + +include::{snippets}/post-update/request-fields.adoc[] + +.Response + +include::{snippets}/post-update/http-response.adoc[] + +.Response Fields + +include::{snippets}/post-update/response-fields.adoc[] \ No newline at end of file diff --git a/src/main/.DS_Store b/src/main/.DS_Store new file mode 100644 index 000000000..e91571673 Binary files /dev/null and b/src/main/.DS_Store differ diff --git a/src/main/java/com/example/board/BoardApplication.java b/src/main/java/com/example/board/BoardApplication.java new file mode 100644 index 000000000..e1328bc56 --- /dev/null +++ b/src/main/java/com/example/board/BoardApplication.java @@ -0,0 +1,15 @@ +package com.example.board; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@EnableJpaAuditing +@SpringBootApplication +public class BoardApplication { + + public static void main(String[] args) { + SpringApplication.run(BoardApplication.class, args); + } + +} diff --git a/src/main/java/com/example/board/configuration/RedisConfiguration.java b/src/main/java/com/example/board/configuration/RedisConfiguration.java new file mode 100644 index 000000000..d7ff3558e --- /dev/null +++ b/src/main/java/com/example/board/configuration/RedisConfiguration.java @@ -0,0 +1,36 @@ +package com.example.board.configuration; + +import com.example.board.model.PostCounter; +import lombok.RequiredArgsConstructor; +import org.springframework.boot.autoconfigure.data.redis.RedisProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +@RequiredArgsConstructor +@Configuration +@EnableRedisRepositories +public class RedisConfiguration { + + private final RedisProperties redisProperties; + + @Bean + public RedisConnectionFactory redisConnectionFactory() { + return new LettuceConnectionFactory(redisProperties.getHost(), redisProperties.getPort()); + } + + @Bean + public RedisTemplate redisTemplate() { + RedisTemplate redisTemplate = new RedisTemplate<>(); + redisTemplate.setKeySerializer(new Jackson2JsonRedisSerializer<>(Long.class)); + redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(PostCounter.class)); + redisTemplate.setConnectionFactory(redisConnectionFactory()); + return redisTemplate; + } +} diff --git a/src/main/java/com/example/board/controller/PostController.java b/src/main/java/com/example/board/controller/PostController.java new file mode 100644 index 000000000..533da75c8 --- /dev/null +++ b/src/main/java/com/example/board/controller/PostController.java @@ -0,0 +1,56 @@ +package com.example.board.controller; + +import com.example.board.dto.PostDetailResponseDto; +import com.example.board.dto.PostCreateDto; +import com.example.board.dto.PostResponseDto; +import com.example.board.dto.PostUpdateDto; +import com.example.board.response.Response; +import com.example.board.service.PostService; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.*; + +import static com.example.board.util.Validation.bindChecking; + +@RequiredArgsConstructor +@RequestMapping("/api/v1/posts") +@RestController +public class PostController { + private final PostService postService; + + @PostMapping + public ResponseEntity> save(@RequestBody @Valid PostCreateDto postDto, BindingResult bindingResult) { + bindChecking(bindingResult); + return ResponseEntity.status(HttpStatus.CREATED) + .body(Response.success(postService.save(postDto))); + } + + @GetMapping + public Response> readAllPost( + @PageableDefault Pageable pageable + ) { + return Response.success(postService.readAllPost(pageable)); + } + + @GetMapping("/{postId}") + public Response readDetailPost(@PathVariable Long postId) { + return Response.success(postService.readPostDetail(postId)); + } + + // TODO: 이후 로그인 정보로 유저 일치 확인하기(변경 예정) + @PatchMapping("/{postId}") + public Response update( + @PathVariable Long postId, + @RequestBody @Valid PostUpdateDto postUpdateDto, + BindingResult bindingResult + ) { + bindChecking(bindingResult); + return Response.success(postService.update(postId, postUpdateDto, postUpdateDto.userId())); + } +} diff --git a/src/main/java/com/example/board/dto/PostCreateDto.java b/src/main/java/com/example/board/dto/PostCreateDto.java new file mode 100644 index 000000000..639b5104f --- /dev/null +++ b/src/main/java/com/example/board/dto/PostCreateDto.java @@ -0,0 +1,19 @@ +package com.example.board.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + +/** + * 추후 게시글 입력 항목 확장을 고려해 PostUpdateDto와 필드는 동일하지만 구분하여 사용할 예정입니다. + */ +public record PostCreateDto( + @NotNull(message = "사용자 id를 입력해주세요.") + Long userId, + @NotBlank(message = "게시글 제목을 입력해주세요.") + @Size(max = 20, message = "제목은 최대 20자까지만 입력해주세요.") + String title, + @NotBlank(message = "게시글 내용을 입력해주세요.") + String contents +) { +} diff --git a/src/main/java/com/example/board/dto/PostDetailResponseDto.java b/src/main/java/com/example/board/dto/PostDetailResponseDto.java new file mode 100644 index 000000000..a6dfb442d --- /dev/null +++ b/src/main/java/com/example/board/dto/PostDetailResponseDto.java @@ -0,0 +1,45 @@ +package com.example.board.dto; + +import com.example.board.exception.BaseException; +import com.example.board.exception.ErrorMessage; +import com.example.board.model.Post; + +public record PostDetailResponseDto( + Long postId, + Long userId, + String userName, + String title, + String contents +) { + + public static PostDetailResponseDto from(Post post) { + postDetailResponseValidate(post); + return new PostDetailResponseDto( + post.getId(), + post.getUser().getId(), + post.getUser().getName(), + post.getTitle(), + post.getContents()); + } + + private static void postDetailResponseValidate(Post post) { + if (post.getId() == null) { + throw new BaseException(ErrorMessage.POST_NOT_FOUND); + } + if (post.getUser() == null) { + throw new BaseException(ErrorMessage.USER_NOT_FOUND); + } + if (post.getUser().getId() == null) { + throw new BaseException(ErrorMessage.WRONG_USER_ID); + } + if (post.getTitle().isBlank() || (post.getTitle().length() > 20)) { + throw new BaseException(ErrorMessage.WRONG_TITLE_VALUE); + } + if (post.getContents().isBlank()) { + throw new BaseException(ErrorMessage.WRONG_CONTENTS_VALUE); + } + if (post.getUser().getName().isBlank()) { + throw new BaseException(ErrorMessage.WRONG_USER_NAME); + } + } +} diff --git a/src/main/java/com/example/board/dto/PostResponseDto.java b/src/main/java/com/example/board/dto/PostResponseDto.java new file mode 100644 index 000000000..d7ab27d59 --- /dev/null +++ b/src/main/java/com/example/board/dto/PostResponseDto.java @@ -0,0 +1,31 @@ +package com.example.board.dto; + +import com.example.board.exception.BaseException; +import com.example.board.exception.ErrorMessage; +import com.example.board.model.Post; + +public record PostResponseDto( + Long postId, + String userName, + String title +) { + public static PostResponseDto from(Post post) { + postResponseValidate(post); + return new PostResponseDto(post.getId(), post.getUser().getName(), post.getTitle()); + } + + private static void postResponseValidate(Post post) { + if (post.getId() == null) { + throw new BaseException(ErrorMessage.POST_NOT_FOUND); + } + if (post.getTitle().isBlank() || (post.getTitle().length() > 20)) { + throw new BaseException(ErrorMessage.WRONG_TITLE_VALUE); + } + if (post.getUser() == null) { + throw new BaseException(ErrorMessage.USER_NOT_FOUND); + } + if (post.getUser().getName().isBlank()) { + throw new BaseException(ErrorMessage.WRONG_USER_NAME); + } + } +} diff --git a/src/main/java/com/example/board/dto/PostUpdateDto.java b/src/main/java/com/example/board/dto/PostUpdateDto.java new file mode 100644 index 000000000..de131ac11 --- /dev/null +++ b/src/main/java/com/example/board/dto/PostUpdateDto.java @@ -0,0 +1,16 @@ +package com.example.board.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + +public record PostUpdateDto( + @NotNull(message = "사용자 id를 입력해주세요.") + Long userId, + @NotBlank(message = "게시글 제목을 입력해주세요.") + @Size(max = 20, message = "제목은 최대 20자까지만 입력해주세요.") + String title, + @NotBlank(message = "게시글 내용을 입력해주세요.") + String contents +) { +} diff --git a/src/main/java/com/example/board/exception/BaseException.java b/src/main/java/com/example/board/exception/BaseException.java new file mode 100644 index 000000000..b53364fb1 --- /dev/null +++ b/src/main/java/com/example/board/exception/BaseException.java @@ -0,0 +1,18 @@ +package com.example.board.exception; + + +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +public class BaseException extends RuntimeException { + private final int code; + private final String message; + private final HttpStatus httpStatus; + + public BaseException(ErrorMessage message) { + this.code = message.getCode(); + this.message = message.getMessage(); + this.httpStatus = message.getHttpStatus(); + } +} diff --git a/src/main/java/com/example/board/exception/BindingException.java b/src/main/java/com/example/board/exception/BindingException.java new file mode 100644 index 000000000..45019d3f4 --- /dev/null +++ b/src/main/java/com/example/board/exception/BindingException.java @@ -0,0 +1,21 @@ +package com.example.board.exception; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +import java.util.List; + +@RequiredArgsConstructor +@Getter +public class BindingException extends RuntimeException { + private final List bindingMessages; + + @Override + public String getMessage() { + String errorMessages = ""; + for (String message : bindingMessages) { + errorMessages += (message + System.lineSeparator()); + } + return errorMessages; + } +} diff --git a/src/main/java/com/example/board/exception/ErrorMessage.java b/src/main/java/com/example/board/exception/ErrorMessage.java new file mode 100644 index 000000000..6185fe677 --- /dev/null +++ b/src/main/java/com/example/board/exception/ErrorMessage.java @@ -0,0 +1,26 @@ +package com.example.board.exception; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum ErrorMessage { + INTERNAL_SERVER_ERROR(500, HttpStatus.INTERNAL_SERVER_ERROR, "서버 내부에서 장애가 발생했습니다."), + // 1xxx user exception + USER_NOT_FOUND(1000, HttpStatus.NOT_FOUND, "찾으시는 사용자가 없습니다."), + WRONG_USER_NAME(1001, HttpStatus.SERVICE_UNAVAILABLE, "사용자 이름이 존재하지 않습니다."), + WRONG_USER_ID(1002, HttpStatus.SERVICE_UNAVAILABLE, "사용자 id 값이 존재하지 않습니다."), + //2xxx post exception + POST_NOT_FOUND(2000, HttpStatus.NOT_FOUND, "찾으시는 게시글이 없습니다."), + WRITER_NOT_MATCHED(2001, HttpStatus.BAD_REQUEST, "작성자가 일치하지 않습니다."), + WRONG_TITLE_VALUE(2002, HttpStatus.BAD_REQUEST, "게시글 제목은 1자~20자 이내로 작성해주십시오."), + WRONG_CONTENTS_VALUE(2003, HttpStatus.BAD_REQUEST, "게시글 내용을 작성해주십시오."), + OVER_MAX_POST_PER_DAY(2004, HttpStatus.BAD_REQUEST, "하루에 작성할 수 있는 최대 게시글 개수를 초과하였습니다."), + OVER_MAX_POST_PER_MINUTE(2005, HttpStatus.BAD_REQUEST, "1분 간 5개 이상의 글을 작성할 수 없습니다."); + + private final int code; + private final HttpStatus httpStatus; + private final String message; +} diff --git a/src/main/java/com/example/board/exception/GlobalExceptionHandler.java b/src/main/java/com/example/board/exception/GlobalExceptionHandler.java new file mode 100644 index 000000000..8dd1eda1c --- /dev/null +++ b/src/main/java/com/example/board/exception/GlobalExceptionHandler.java @@ -0,0 +1,36 @@ +package com.example.board.exception; + +import com.example.board.response.Response; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + @ExceptionHandler(BaseException.class) + public ResponseEntity> baseExceptionHandle(BaseException e) { + log.info("error: {}", e.getMessage()); + return ResponseEntity.status(e.getHttpStatus()).body(Response.fail(e)); + } + + @ExceptionHandler(RuntimeException.class) + public ResponseEntity> runtimeExceptionHandle(RuntimeException e) { + log.info("error: {}", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Response.fail(e)); + } + + @ExceptionHandler(BindingException.class) + public ResponseEntity> bindingExceptionHandle(BindingException e) { + log.info("error: {}", e.getMessage()); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Response.fail(e.getBindingMessages())); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity> exceptionHandle(Exception e) { + log.info("error: {}", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Response.fail(e)); + } +} diff --git a/src/main/java/com/example/board/model/BaseEntity.java b/src/main/java/com/example/board/model/BaseEntity.java new file mode 100644 index 000000000..5ca802569 --- /dev/null +++ b/src/main/java/com/example/board/model/BaseEntity.java @@ -0,0 +1,21 @@ +package com.example.board.model; + +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@Getter +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public class BaseEntity { + @CreatedDate + private LocalDateTime createdAt; + + @LastModifiedDate + private LocalDateTime updatedAt; +} diff --git a/src/main/java/com/example/board/model/Post.java b/src/main/java/com/example/board/model/Post.java new file mode 100644 index 000000000..ee1e31e8d --- /dev/null +++ b/src/main/java/com/example/board/model/Post.java @@ -0,0 +1,78 @@ +package com.example.board.model; + +import com.example.board.dto.PostCreateDto; +import com.example.board.dto.PostUpdateDto; +import com.example.board.exception.BaseException; +import com.example.board.exception.ErrorMessage; +import io.micrometer.common.util.StringUtils; +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Entity +@Table(name = "posts") +public class Post extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "post_id") + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + @Column(name = "title", length = 30) + private String title; + + @Lob + private String contents; + + @Column(name = "created_by") + private String createdBy; + + private Post(User user, PostCreateDto postDto) { + postSaveValidate(user, postDto); + this.user = user; + this.title = postDto.title(); + this.contents = postDto.contents(); + this.createdBy = user.getName(); + } + + public static Post from(User user, PostCreateDto postDto) { + return new Post(user, postDto); + } + + public Long update(PostUpdateDto postUpdateDto) { + postUpdateValidate(postUpdateDto); + this.title = postUpdateDto.title(); + this.contents = postUpdateDto.contents(); + return this.id; + } + + private static void postSaveValidate(User user, PostCreateDto postDto) { + if (user == null) { + throw new BaseException(ErrorMessage.USER_NOT_FOUND); + } + if (StringUtils.isBlank(postDto.title()) || (postDto.title().length() > 20)) { + throw new BaseException(ErrorMessage.WRONG_TITLE_VALUE); + } + if (StringUtils.isBlank(postDto.contents())) { + throw new BaseException(ErrorMessage.WRONG_CONTENTS_VALUE); + } + if (StringUtils.isBlank(user.getName())) { + throw new BaseException(ErrorMessage.WRONG_USER_NAME); + } + } + + private static void postUpdateValidate(PostUpdateDto postUpdateDto) { + if (StringUtils.isBlank(postUpdateDto.title()) || (postUpdateDto.title().length() > 20)) { + throw new BaseException(ErrorMessage.WRONG_TITLE_VALUE); + } + if (StringUtils.isBlank(postUpdateDto.contents())) { + throw new BaseException(ErrorMessage.WRONG_CONTENTS_VALUE); + } + } +} diff --git a/src/main/java/com/example/board/model/PostCounter.java b/src/main/java/com/example/board/model/PostCounter.java new file mode 100644 index 000000000..d92a2ba58 --- /dev/null +++ b/src/main/java/com/example/board/model/PostCounter.java @@ -0,0 +1,71 @@ +package com.example.board.model; + +import com.example.board.exception.BaseException; +import com.example.board.exception.ErrorMessage; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; +import lombok.Getter; + +import java.time.LocalDateTime; + +@Getter +public class PostCounter { + private Long userId; + private int totalWriteInDay; + @JsonSerialize(using = LocalDateTimeSerializer.class) + @JsonDeserialize(using = LocalDateTimeDeserializer.class) + private LocalDateTime lastPostedAt; + private int totalWritePerMit; + @JsonSerialize(using = LocalDateTimeSerializer.class) + @JsonDeserialize(using = LocalDateTimeDeserializer.class) + private LocalDateTime lastPostedInMin; + + private PostCounter(Long userId) { + this.userId = userId; + this.totalWriteInDay = 1; + this.lastPostedAt = LocalDateTime.now(); + this.totalWritePerMit = 1; + this.lastPostedInMin = LocalDateTime.now(); + } + + public static PostCounter firstPostInDay(Long userId) { + return new PostCounter(userId); + } + + public void update() { + if (totalWriteInDay >= 9) { + throw new BaseException(ErrorMessage.OVER_MAX_POST_PER_DAY); + } + if (checkWritesInMinuteOverCountFour()) return; + if (lastPostedAt.plusMinutes(1).isAfter(LocalDateTime.now())) { + totalWritePerMit++; + totalWriteInDay++; + lastPostedAt = LocalDateTime.now(); + return; + } + writeTimeOverMinute(); + + } + + private boolean checkWritesInMinuteOverCountFour() { + if (totalWritePerMit >= 4) { + if (writeTimeOverMinute()) return true; + throw new BaseException(ErrorMessage.OVER_MAX_POST_PER_MINUTE); + } + return false; + } + + private boolean writeTimeOverMinute() { + if (lastPostedAt.plusMinutes(1).isBefore(LocalDateTime.now())) { + totalWritePerMit = 1; + totalWriteInDay++; + lastPostedAt = LocalDateTime.now(); + lastPostedInMin = lastPostedAt; + return true; + } + ; + return false; + } +} diff --git a/src/main/java/com/example/board/model/User.java b/src/main/java/com/example/board/model/User.java new file mode 100644 index 000000000..be51db1e6 --- /dev/null +++ b/src/main/java/com/example/board/model/User.java @@ -0,0 +1,28 @@ +package com.example.board.model; + +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@EqualsAndHashCode(callSuper = true) +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Entity +@Table(name = "users") +public class User extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "user_id") + private Long id; + + @Column(name = "name", length = 20) + private String name; + + @Column(name = "age") + private int age; + + @Column(name = "hobby", length = 40) + private String hobby; +} diff --git a/src/main/java/com/example/board/repository/PostCounterRedisRepository.java b/src/main/java/com/example/board/repository/PostCounterRedisRepository.java new file mode 100644 index 000000000..adef64a2f --- /dev/null +++ b/src/main/java/com/example/board/repository/PostCounterRedisRepository.java @@ -0,0 +1,24 @@ +package com.example.board.repository; + +import com.example.board.model.PostCounter; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +@RequiredArgsConstructor +public class PostCounterRedisRepository { + + private final RedisTemplate redisTemplate; + + public Optional getPostCounter(Long userId){ + PostCounter postCounter = redisTemplate.opsForValue().get(userId); + return Optional.ofNullable(postCounter); + } + + public void savePostCounter(Long userId, PostCounter postCounter){ + redisTemplate.opsForValue().set(userId, postCounter); + } +} diff --git a/src/main/java/com/example/board/repository/PostRepository.java b/src/main/java/com/example/board/repository/PostRepository.java new file mode 100644 index 000000000..145bbf261 --- /dev/null +++ b/src/main/java/com/example/board/repository/PostRepository.java @@ -0,0 +1,21 @@ +package com.example.board.repository; + +import com.example.board.model.Post; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.Optional; + +public interface PostRepository extends JpaRepository { + @EntityGraph(attributePaths = "user") + @Query("select p from Post p ") + Page findAllByEntityGraph(Pageable pageable); + + @EntityGraph(attributePaths = "user") + @Query("select p from Post p where p.id = :postId") + Optional findByIdEntityGraph(@Param("postId") Long postId); +} diff --git a/src/main/java/com/example/board/repository/UserRepository.java b/src/main/java/com/example/board/repository/UserRepository.java new file mode 100644 index 000000000..0df2c4b17 --- /dev/null +++ b/src/main/java/com/example/board/repository/UserRepository.java @@ -0,0 +1,7 @@ +package com.example.board.repository; + +import com.example.board.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} diff --git a/src/main/java/com/example/board/response/Response.java b/src/main/java/com/example/board/response/Response.java new file mode 100644 index 000000000..a129ab8c0 --- /dev/null +++ b/src/main/java/com/example/board/response/Response.java @@ -0,0 +1,21 @@ +package com.example.board.response; +import com.example.board.exception.BaseException; +import java.util.List; + +public record Response(T data, int code, String isSuccess) { + public static Response success(T data) { + return new Response<>(data, 200, "ok"); + } + + public static Response fail(BaseException e) { + return new Response<>(e.getMessage(), e.getCode(), "fail"); + } + + public static Response fail(Exception e) { + return new Response<>(e.getMessage(), 500, "fail"); + } + + public static Response> fail(List bindingErrors) { + return new Response<>(bindingErrors, 400, "fail"); + } +} diff --git a/src/main/java/com/example/board/service/PostService.java b/src/main/java/com/example/board/service/PostService.java new file mode 100644 index 000000000..8fd83e7a8 --- /dev/null +++ b/src/main/java/com/example/board/service/PostService.java @@ -0,0 +1,56 @@ +package com.example.board.service; + +import com.example.board.dto.PostDetailResponseDto; +import com.example.board.dto.PostCreateDto; +import com.example.board.dto.PostResponseDto; +import com.example.board.dto.PostUpdateDto; +import com.example.board.exception.BaseException; +import com.example.board.exception.ErrorMessage; +import com.example.board.model.Post; +import com.example.board.model.User; +import com.example.board.repository.PostRepository; +import com.example.board.repository.UserRepository; +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; + +@RequiredArgsConstructor +@Service +public class PostService { + private final PostRepository postRepository; + private final UserRepository userRepository; + private final RedisService redisService; + + @Transactional + public Long save(PostCreateDto postDto) { + User user = userRepository.findById(postDto.userId()).orElseThrow(() -> + new BaseException(ErrorMessage.USER_NOT_FOUND) + ); + redisService.postInfoChecking(user); + return postRepository.save(Post.from(user, postDto)).getId(); + } + + public Page readAllPost(Pageable pageable) { + return postRepository.findAllByEntityGraph(pageable).map(PostResponseDto::from); + } + + public PostDetailResponseDto readPostDetail(Long postId) { + return PostDetailResponseDto.from(postRepository.findByIdEntityGraph(postId) + .orElseThrow(() -> new BaseException(ErrorMessage.POST_NOT_FOUND))); + } + + @Transactional + public Long update(Long postId, PostUpdateDto postUpdateDto, Long userId) { + Post post = postRepository.findByIdEntityGraph(postId) + .orElseThrow(() -> new BaseException(ErrorMessage.POST_NOT_FOUND)); + User user = userRepository.findById(userId) + .orElseThrow(() -> new BaseException(ErrorMessage.USER_NOT_FOUND)); + + if (!post.getUser().equals(user)) { + throw new BaseException(ErrorMessage.WRITER_NOT_MATCHED); + } + return post.update(postUpdateDto); + } +} diff --git a/src/main/java/com/example/board/service/RedisService.java b/src/main/java/com/example/board/service/RedisService.java new file mode 100644 index 000000000..63c31f70a --- /dev/null +++ b/src/main/java/com/example/board/service/RedisService.java @@ -0,0 +1,29 @@ +package com.example.board.service; + +import com.example.board.model.PostCounter; +import com.example.board.model.User; +import com.example.board.repository.PostCounterRedisRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class RedisService { + private final PostCounterRedisRepository redisRepository; + + public void postInfoChecking(User user){ + redisRepository.getPostCounter(user.getId()) + .ifPresentOrElse( + postCounter -> updateSavedData(postCounter, user.getId()), + () -> redisRepository.savePostCounter( + user.getId(), + PostCounter.firstPostInDay(user.getId()))); + } + + private void updateSavedData(PostCounter postCounter, Long userId){ + postCounter.update(); + redisRepository.savePostCounter(userId, postCounter); + } + + +} diff --git a/src/main/java/com/example/board/util/Validation.java b/src/main/java/com/example/board/util/Validation.java new file mode 100644 index 000000000..8ebbcf338 --- /dev/null +++ b/src/main/java/com/example/board/util/Validation.java @@ -0,0 +1,24 @@ +package com.example.board.util; + +import com.example.board.exception.BindingException; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import org.springframework.validation.BindingResult; + +import java.util.ArrayList; +import java.util.List; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class Validation { + public static void bindChecking(BindingResult bindingResult) { + List messages = new ArrayList<>(); + if (bindingResult.hasErrors()) { + bindingResult.getAllErrors().forEach(objectError -> { + messages.add(objectError.getDefaultMessage()); + }); + } + if (!messages.isEmpty()) { + throw new BindingException(messages); + } + } +} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 000000000..c586848bf --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,27 @@ +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3308/board + username: root + password: root + jpa: + show-sql: true + data: + redis: + host: localhost + port: 6830 + + +--- + +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3308/board_test + username: root + password: root + jpa: + show-sql: true + config: + activate: + on-profile: test \ No newline at end of file diff --git a/src/test/java/com/example/board/BoardApplicationTests.java b/src/test/java/com/example/board/BoardApplicationTests.java new file mode 100644 index 000000000..ea4d16397 --- /dev/null +++ b/src/test/java/com/example/board/BoardApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.board; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class BoardApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/example/board/controller/PostControllerTest.java b/src/test/java/com/example/board/controller/PostControllerTest.java new file mode 100644 index 000000000..72b6dc4ef --- /dev/null +++ b/src/test/java/com/example/board/controller/PostControllerTest.java @@ -0,0 +1,382 @@ +package com.example.board.controller; + +import com.example.board.dto.PostCreateDto; +import com.example.board.dto.PostUpdateDto; +import com.example.board.response.Response; +import com.example.board.service.PostService; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; +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.payload.JsonFieldType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.payload.PayloadDocumentation.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureRestDocs +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +class PostControllerTest { + + @Autowired + PostController postController; + @Autowired + ObjectMapper objectMapper; + @Autowired + PostService postService; + @Autowired + MockMvc mockMvc; + + @Nested + @DisplayName("게시글 등록") + class PostNew { + @Test + @DisplayName("정상적으로 게시글을 등록된다.") + void saveSuccess() throws Exception { + //given + PostCreateDto postDto = new PostCreateDto(1L, "test2", "test Contents2"); + + //when, then + mockMvc.perform(post("http://localhost:8080/api/v1/posts") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsBytes(postDto))) + .andExpect(status().isOk()) + .andDo(document("post-save", + requestFields( + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("userId"), + fieldWithPath("title").type(JsonFieldType.STRING).description("title"), + fieldWithPath("contents").type(JsonFieldType.STRING).description("contents") + ), + responseFields( + fieldWithPath("code").type(JsonFieldType.NUMBER).description("statusCode"), + fieldWithPath("data").type(JsonFieldType.NUMBER).description("postId"), + fieldWithPath("isSuccess").type(JsonFieldType.STRING).description("isSuccess") + ) + )); + } + + @Test + @DisplayName("userId를 포함하지 않고 보낼 경우 예외가 발생한다.") + void saveFailWithAnonymousUser() throws Exception { + //given + PostCreateDto postDto = new PostCreateDto(null, "test2", "test Contents2"); + + //when, then + String response = mockMvc.perform(post("http://localhost:8080/api/v1/posts") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsBytes(postDto))) + .andExpect(status().isBadRequest()) + .andDo(print()) + .andReturn() + .getResponse() + .getContentAsString(StandardCharsets.UTF_8); + Response> exception = objectMapper.readValue(response, Response.class); + assertThat(exception.data().get(0)).isEqualTo("사용자 id를 입력해주세요."); + assertThat(exception.code()).isEqualTo(400); + } + + @Test + @DisplayName("존재하지 않는 userId를 보낼 경우 예외가 발생한다.") + void saveFailWithWrongUser() throws Exception { + //given + PostCreateDto postDto = new PostCreateDto(0L, "test2", "test Contents2"); + + //when, then + String response = mockMvc.perform(post("http://localhost:8080/api/v1/posts") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsBytes(postDto))) + .andExpect(status().isNotFound()) + .andDo(print()) + .andReturn() + .getResponse() + .getContentAsString(StandardCharsets.UTF_8); + Response exception = objectMapper.readValue(response, Response.class); + assertThat(exception.code()).isEqualTo(1000); + } + + @Test + @DisplayName("제목이 20자 이상인 경우 예외를 발생시킨다.") + void saveFailWithLongTitle() throws Exception { + //given + PostCreateDto postDto = new PostCreateDto(1L, "test222222222222222222222222", "test Contents2"); + + //when, then + String response = mockMvc.perform(post("http://localhost:8080/api/v1/posts") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsBytes(postDto))) + .andExpect(status().isBadRequest()) + .andDo(print()) + .andReturn() + .getResponse() + .getContentAsString(StandardCharsets.UTF_8); + Response> exception = objectMapper.readValue(response, Response.class); + assertThat(exception.data().get(0)).isEqualTo("제목은 최대 20자까지만 입력해주세요."); + assertThat(exception.code()).isEqualTo(400); + } + + + @ParameterizedTest(name = "title이 `{0}`인 경우 저장 요청에 실패한다.") + @ValueSource(strings = {" "}) + @NullAndEmptySource + @DisplayName("제목이 없는 경우 예외를 발생시킨다.") + void saveFailWithNoTitle(String input) throws Exception { + //given + PostCreateDto postDto = new PostCreateDto(1L, input, "test Contents2"); + + //when, then + String response = mockMvc.perform(post("http://localhost:8080/api/v1/posts") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsBytes(postDto))) + .andExpect(status().isBadRequest()) + .andDo(print()) + .andReturn() + .getResponse() + .getContentAsString(StandardCharsets.UTF_8); + Response> exception = objectMapper.readValue(response, Response.class); + assertThat(exception.data().get(0)).isEqualTo("게시글 제목을 입력해주세요."); + assertThat(exception.code()).isEqualTo(400); + } + + @ParameterizedTest(name = "contents가 `{0}`인 경우 저장 요청에 실패한다.") + @ValueSource(strings = {" "}) + @NullAndEmptySource + @DisplayName("내용이 없는 경우 예외를 발생시킨다.") + void saveFailWithNoContents(String input) throws Exception { + //given + PostCreateDto postDto = new PostCreateDto(1L, "title", input); + + //when, then + String response = mockMvc.perform(post("http://localhost:8080/api/v1/posts") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsBytes(postDto))) + .andExpect(status().isBadRequest()) + .andDo(print()) + .andReturn() + .getResponse() + .getContentAsString(StandardCharsets.UTF_8); + Response> exception = objectMapper.readValue(response, Response.class); + assertThat(exception.data().get(0)).isEqualTo("게시글 내용을 입력해주세요."); + assertThat(exception.code()).isEqualTo(400); + } + } + + @Nested + @DisplayName("게시글 전체 조회") + class PostGetAll { + @Test + @DisplayName("정상적으로 모든 게시물들을 받아온다.") + void getSuccess() throws Exception { + //given + postService.save(new PostCreateDto(1L, "testTitle1", "hihihihihihihih1")); + postService.save(new PostCreateDto(1L, "testTitle2", "hihihihihihihih2")); + + //when, then + mockMvc.perform(get("http://localhost:8080/api/v1/posts") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("post-getAll", + responseFields( + fieldWithPath("code").type(JsonFieldType.NUMBER).description("statusCode"), + fieldWithPath("data").type(JsonFieldType.OBJECT).description("contents-list"), + fieldWithPath("data.content[]").type(JsonFieldType.ARRAY).description("contents-list"), + fieldWithPath("data.content[].postId").type(JsonFieldType.NUMBER).description("postId"), + fieldWithPath("data.content[].userName").type(JsonFieldType.STRING).description("username"), + fieldWithPath("data.content[].title").type(JsonFieldType.STRING).description("title"), + fieldWithPath("data.content[].postId").type(JsonFieldType.NUMBER).description("postId"), + fieldWithPath("data.content[].userName").type(JsonFieldType.STRING).description("username"), + fieldWithPath("data.content[].title").type(JsonFieldType.STRING).description("title"), + fieldWithPath("data.pageable").type(JsonFieldType.OBJECT).description("pageable"), + fieldWithPath("data.pageable.pageNumber").type(JsonFieldType.NUMBER).description("pageNumber"), + fieldWithPath("data.pageable.pageSize").type(JsonFieldType.NUMBER).description("pageSize"), + fieldWithPath("data.pageable.sort").type(JsonFieldType.OBJECT).description("sort"), + fieldWithPath("data.pageable.sort.empty").type(JsonFieldType.BOOLEAN).description("empty"), + fieldWithPath("data.pageable.sort.unsorted").type(JsonFieldType.BOOLEAN).description("unsorted"), + fieldWithPath("data.pageable.sort.sorted").type(JsonFieldType.BOOLEAN).description("sorted"), + fieldWithPath("data.pageable.offset").type(JsonFieldType.NUMBER).description("offset"), + fieldWithPath("data.pageable.paged").type(JsonFieldType.BOOLEAN).description("paged"), + fieldWithPath("data.pageable.unpaged").type(JsonFieldType.BOOLEAN).description("unpaged"), + fieldWithPath("data.totalPages").type(JsonFieldType.NUMBER).description("totalPages"), + fieldWithPath("data.totalElements").type(JsonFieldType.NUMBER).description("totalElements"), + fieldWithPath("data.last").type(JsonFieldType.BOOLEAN).description("last"), + fieldWithPath("data.size").type(JsonFieldType.NUMBER).description("size"), + fieldWithPath("data.number").type(JsonFieldType.NUMBER).description("number"), + fieldWithPath("data.sort").type(JsonFieldType.OBJECT).description("sort"), + fieldWithPath("data.sort.empty").type(JsonFieldType.BOOLEAN).description("empty"), + fieldWithPath("data.sort.sorted").type(JsonFieldType.BOOLEAN).description("sorted"), + fieldWithPath("data.sort.unsorted").type(JsonFieldType.BOOLEAN).description("unsorted"), + fieldWithPath("data.numberOfElements").type(JsonFieldType.NUMBER).description("numberOfElements"), + fieldWithPath("data.first").type(JsonFieldType.BOOLEAN).description("first"), + fieldWithPath("data.empty").type(JsonFieldType.BOOLEAN).description("unpaged"), + fieldWithPath("isSuccess").type(JsonFieldType.STRING).description("isSuccess") + ) + )); + } + } + + @Nested + @DisplayName("게시글 단건 조회") + class PostGetOne { + @Test + @DisplayName("정상적으로 특정 게시물 하나를 받아온다.") + void getByIdSuccess() throws Exception { + //given + Long savedContentsId = postService.save(new PostCreateDto(1L, "testTitle", "hihihihihihihih")); + + //when, then + mockMvc.perform(get("http://localhost:8080/api/v1/posts/" + savedContentsId) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("post-getById", + responseFields( + fieldWithPath("code").type(JsonFieldType.NUMBER).description("statusCode"), + fieldWithPath("data").type(JsonFieldType.OBJECT).description("contents-list"), + fieldWithPath("data.userName").type(JsonFieldType.STRING).description("username"), + fieldWithPath("data.postId").type(JsonFieldType.NUMBER).description("postId"), + fieldWithPath("data.userId").type(JsonFieldType.NUMBER).description("userId"), + fieldWithPath("data.title").type(JsonFieldType.STRING).description("title"), + fieldWithPath("data.contents").type(JsonFieldType.STRING).description("contents"), + fieldWithPath("isSuccess").type(JsonFieldType.STRING).description("isSuccess") + ) + )); + } + + @Test + @DisplayName("존재하지 않는 게시물을 호출하여 예외가 발생하였다.") + void getByIdNotFoundFail() throws Exception { + //given + + //when + String response = mockMvc.perform(get("http://localhost:8080/api/v1/posts/" + "0") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()) + .andDo(print()) + .andReturn() + .getResponse() + .getContentAsString(StandardCharsets.UTF_8); + Response exception = objectMapper.readValue(response, Response.class); + + //then + assertThat(exception.code()).isEqualTo(2000); + + } + } + + @Nested + @DisplayName("게시글 수정") + class PostUpdate { + @Test + @DisplayName("정상적으로 게시글을 수정한다.") + void updateSuccess() throws Exception { + //given + Long savedContents = postService.save(new PostCreateDto(1L, "testTitle", "hihihihihihihih")); + + PostUpdateDto postUpdateDto = new PostUpdateDto(1L, "test2", "test Contents2"); + + //when, then + mockMvc.perform(patch("http://localhost:8080/api/v1/posts/" + savedContents) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsBytes(postUpdateDto))) + .andExpect(status().isOk()) + .andDo(document("post-update", + requestFields( + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("userId"), + fieldWithPath("title").type(JsonFieldType.STRING).description("title update"), + fieldWithPath("contents").type(JsonFieldType.STRING).description("contents update") + ), + responseFields( + fieldWithPath("code").type(JsonFieldType.NUMBER).description("statusCode"), + fieldWithPath("data").type(JsonFieldType.NUMBER).description("postId"), + fieldWithPath("isSuccess").type(JsonFieldType.STRING).description("isSuccess") + ) + )); + } + + @Test + @DisplayName("수정 시 제목이 20자 이상인 경우 예외를 발생시킨다.") + void updateFailWithLongTitle() throws Exception { + //given + Long savedContents = postService.save(new PostCreateDto(1L, "testTitle", "hihihihihihihih")); + PostUpdateDto postDto = new PostUpdateDto(1L, "test222222222222222222222222", "test Contents2"); + + //when, then + String response = mockMvc.perform(patch("http://localhost:8080/api/v1/posts/" + savedContents) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsBytes(postDto))) + .andExpect(status().isBadRequest()) + .andDo(print()) + .andReturn() + .getResponse() + .getContentAsString(StandardCharsets.UTF_8); + Response> exception = objectMapper.readValue(response, Response.class); + assertThat(exception.data().get(0)).isEqualTo("제목은 최대 20자까지만 입력해주세요."); + assertThat(exception.code()).isEqualTo(400); + } + + + @ParameterizedTest(name = "title이 `{0}`인 경우 수정 요청에 실패한다.") + @ValueSource(strings = {" "}) + @NullAndEmptySource + @DisplayName("수정 시 제목이 없는 경우 예외를 발생시킨다.") + void updateFailWithNoTitle(String input) throws Exception { + //given + Long savedContents = postService.save(new PostCreateDto(1L, "testTitle", "hihihihihihihih")); + PostCreateDto postDto = new PostCreateDto(1L, input, "test Contents2"); + + //when, then + String response = mockMvc.perform(patch("http://localhost:8080/api/v1/posts/" + savedContents) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsBytes(postDto))) + .andExpect(status().isBadRequest()) + .andDo(print()) + .andReturn() + .getResponse() + .getContentAsString(StandardCharsets.UTF_8); + Response> exception = objectMapper.readValue(response, Response.class); + assertThat(exception.data().get(0)).isEqualTo("게시글 제목을 입력해주세요."); + assertThat(exception.code()).isEqualTo(400); + } + + @ParameterizedTest(name = "contents가 `{0}`인 경우 수정 요청에 실패한다.") + @ValueSource(strings = {" "}) + @NullAndEmptySource + @DisplayName("수정 시 내용이 없는 경우 예외를 발생시킨다.") + void updateFailWithNoContents(String input) throws Exception { + //given + Long savedContents = postService.save(new PostCreateDto(1L, "testTitle", "hihihihihihihih")); + PostCreateDto postDto = new PostCreateDto(1L, "title", input); + + //when, then + String response = mockMvc.perform(patch("http://localhost:8080/api/v1/posts/" + savedContents) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsBytes(postDto))) + .andExpect(status().isBadRequest()) + .andDo(print()) + .andReturn() + .getResponse() + .getContentAsString(StandardCharsets.UTF_8); + Response> exception = objectMapper.readValue(response, Response.class); + assertThat(exception.data().get(0)).isEqualTo("게시글 내용을 입력해주세요."); + assertThat(exception.code()).isEqualTo(400); + } + } +} diff --git a/src/test/java/com/example/board/model/PostTest.java b/src/test/java/com/example/board/model/PostTest.java new file mode 100644 index 000000000..16de0cffe --- /dev/null +++ b/src/test/java/com/example/board/model/PostTest.java @@ -0,0 +1,177 @@ +package com.example.board.model; + +import com.example.board.dto.PostCreateDto; +import com.example.board.dto.PostUpdateDto; +import com.example.board.exception.BaseException; +import com.example.board.exception.ErrorMessage; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mock; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.List; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.when; + +@ExtendWith(SpringExtension.class) +class PostTest { + + @Mock + User mockUser; + + static Post featurePost; + + @BeforeEach + void setup(){ + when(mockUser.getId()).thenReturn(1L); + when(mockUser.getName()).thenReturn("mockUser"); + featurePost = Post.from(mockUser, new PostCreateDto(mockUser.getId(), "title", "contents")); + } + + @Nested + @DisplayName("Post save 시 생성하는 객체 유효성 검사 테스트") + class PostCreate { + private static List invalidTitle() { + String string = "asdf"; + return List.of(string.repeat(6)); + } + + @Test + @DisplayName("post 생성 시 정상적으로 저장을 위한 Post 객체가 생성되는 경우") + void saveEntitySuccess() { + // given + PostCreateDto postDto = new PostCreateDto(mockUser.getId(), "title", "contents"); + + //when + Post post = Post.from(mockUser, postDto); + + //then + assertThat(post.getTitle()).isEqualTo(postDto.title()); + assertThat(post.getContents()).isEqualTo(postDto.contents()); + } + + //TODO: 이 테스트를 유지하는 것이 맞는가, 너무 억지스럽게 된 것 같다. + @Test + @DisplayName("post 생성 시 User 객체가 null 값이라 불러올 수 없는 경우") + void saveEntityFailWithNullUser() { + PostCreateDto postDto = new PostCreateDto(mockUser.getId(), "title", "contents"); + mockUser = null; + + //when + assertThatThrownBy(() ->Post.from(mockUser, postDto)) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.USER_NOT_FOUND.getMessage()); + + } + + @ParameterizedTest(name = "title이 `{0}`인 경우 저장을 위한 객체 생성이 실패한다.") + @ValueSource(strings = {" "}) + @MethodSource("invalidTitle") + @NullAndEmptySource + @DisplayName("post 생성 시 제목이 null, 빈 공백, 20자 이상인 경우 post 객체 생성에 실패한다.") + void saveEntityFailWithInvalidTitle(String input) { + // given + PostCreateDto postDto = new PostCreateDto(1L, input, "test Contents"); + + // when, then + assertThatThrownBy(() -> Post.from(mockUser, postDto)) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.WRONG_TITLE_VALUE.getMessage()); + } + + @ParameterizedTest(name = "contents가 `{0}`인 경우 저장을 위한 객체 생성이 실패한다.") + @ValueSource(strings = {" "}) + @NullAndEmptySource + @DisplayName("post 생성 시 본문 내용이 null, 빈 공백인 경우 post 객체 생성에 실패한다.") + void saveEntityFailWithInvalidContents(String input) { + // given + PostCreateDto postDto = new PostCreateDto(1L, "title", input); + + // when, then + assertThatThrownBy(() -> Post.from(mockUser, postDto)) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.WRONG_CONTENTS_VALUE.getMessage()); + } + + @ParameterizedTest(name = "user의 이름이 `{0}`인 경우 저장을 위한 객체 생성이 실패한다.") + @ValueSource(strings = {" "}) + @NullAndEmptySource + @DisplayName("post 생성 시 본문 수정 시 저장하는 user의 이름이 null, 빈 공백인 경우 post 객체 생성에 실패한다.") + void saveEntityFailWithInvalidUserName(String input) { + // given + when(mockUser.getName()).thenReturn(input); + PostCreateDto postDto = new PostCreateDto(mockUser.getId(), "title", "contents"); + + //when + assertThatThrownBy(() -> Post.from(mockUser, postDto)) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.WRONG_USER_NAME.getMessage()); + } + } + + @Nested + @DisplayName("Post update 시 생성하는 객체 유효성 검사 테스트") + class PostUpdate { + private static List invalidTitle() { + String string = "asdf"; + return List.of(string.repeat(6)); + } + + @Test + @DisplayName("post 수정 시 정상적으로 수정을 위한 Post 객체가 생성되는 경우") + void saveEntitySuccess() { + // given + when(mockUser.getId()).thenReturn(1L); + when(mockUser.getName()).thenReturn("mock user"); + + PostCreateDto postDto = new PostCreateDto(mockUser.getId(), "title", "contents"); + + Post post = Post.from(mockUser, postDto); + + PostUpdateDto updateDto = new PostUpdateDto(mockUser.getId(), "title", "contents"); + + //when + post.update(updateDto); + + //then + assertThat(post.getTitle()).isEqualTo(updateDto.title()); + assertThat(post.getContents()).isEqualTo(updateDto.contents()); + } + + @ParameterizedTest(name = "title이 `{0}`인 경우 저장을 위한 객체 생성이 실패한다.") + @ValueSource(strings = {" "}) + @MethodSource("invalidTitle") + @NullAndEmptySource + @DisplayName("post 수정 시 제목이 null, 빈 공백, 20자 이상인 경우 post 객체 생성에 실패한다.") + void saveEntityFailWithInvalidTitle(String input) { + // given + PostUpdateDto updateDto = new PostUpdateDto(mockUser.getId(), input, "test Contents"); + + // when, then + assertThatThrownBy(() -> featurePost.update(updateDto)) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.WRONG_TITLE_VALUE.getMessage()); + } + + @ParameterizedTest(name = "contents가 `{0}`인 경우 저장을 위한 객체 생성이 실패한다.") + @ValueSource(strings = {" "}) + @NullAndEmptySource + @DisplayName("본문 수정 시 내용이 null, 빈 공백인 경우 post 객체 생성에 실패한다.") + void updateEntityFailWithInvalidContents(String input) { + // given + PostUpdateDto postDto = new PostUpdateDto(1L, "title", input); + + // when, then + assertThatThrownBy(() -> featurePost.update(postDto)) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.WRONG_CONTENTS_VALUE.getMessage()); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/com/example/board/service/PostServiceTest.java b/src/test/java/com/example/board/service/PostServiceTest.java new file mode 100644 index 000000000..3829841f5 --- /dev/null +++ b/src/test/java/com/example/board/service/PostServiceTest.java @@ -0,0 +1,251 @@ +package com.example.board.service; + +import com.example.board.dto.PostDetailResponseDto; +import com.example.board.dto.PostCreateDto; +import com.example.board.dto.PostResponseDto; +import com.example.board.dto.PostUpdateDto; +import com.example.board.exception.BaseException; +import com.example.board.exception.ErrorMessage; +import com.example.board.model.Post; +import com.example.board.repository.PostRepository; +import com.example.board.repository.UserRepository; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@ActiveProfiles("test") +@SpringBootTest +@Transactional +class PostServiceTest { + + @Autowired + PostService postService; + + @Autowired + PostRepository postRepository; + + @Autowired + UserRepository userRepository; + + @Nested + @DisplayName("게시글 생성") + class PostNew { + @Test + @DisplayName("정상적으로 PostDto를 받아 글 작성을 완료하는 경우") + void saveSuccessInService() { + PostCreateDto postDto = new PostCreateDto(1L, "test", "test Contents"); + + Long save = postService.save(postDto); + Optional savedPosts = postRepository.findById(save); + + assertThat(savedPosts).isNotEmpty(); + } + + @Test + @DisplayName("제목이 20자 이상인 경우 실패한다.") + void saveFailByTitleLength() { + // given + PostCreateDto postDto = new PostCreateDto(1L, "testtesttesttesttesttesttest", "test Contents"); + + // when, then + assertThatThrownBy(() -> postService.save(postDto)) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.WRONG_TITLE_VALUE.getMessage()); + } + + @ParameterizedTest(name = "title이 `{0}`인 경우 저장 로직에서 실패한다.") + @ValueSource(strings = {" ", " "}) + @NullAndEmptySource + @DisplayName("제목이 null이거나 빈 공백인 경우 실패한다.") + void saveFailByTitleNullOrBlank(String input) { + // given + PostCreateDto postDto = new PostCreateDto(1L, input, "test Contents"); + + // when, then + assertThatThrownBy(() -> postService.save(postDto)) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.WRONG_TITLE_VALUE.getMessage()); + } + + @ParameterizedTest(name = "contents가 `{0}`인 경우 저장 로직에서 실패한다.") + @ValueSource(strings = {" ", " "}) + @NullAndEmptySource + @DisplayName("내용이 null이거나 빈 공백인 경우 실패한다.") + void saveFailByContents(String input) { + // given + PostCreateDto postDto = new PostCreateDto(1L, "title", input); + + // when, then + assertThatThrownBy(() -> postService.save(postDto)) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.WRONG_CONTENTS_VALUE.getMessage()); + } + + @Test + @DisplayName("존재하지 않는 유저가 글을 작성하는 경우 예외를 발생시킨다.") + void saveFailWithAnonymousUser() { + PostCreateDto postDto = new PostCreateDto(0L, "test", "test Contents"); + + assertThatThrownBy(() -> postService.save(postDto)) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.USER_NOT_FOUND.getMessage()); + } + } + + @Nested + @DisplayName("게시글 전체 조회") + class PostGetAll { + @Test + @DisplayName("정상적으로 모든 게시물들을 받아온다.") + void getAllSuccess() { + for (int i = 0; i < 15; i++) { + PostCreateDto postDto = new PostCreateDto(1L, "title" + i, "contents" + i); + postService.save(postDto); + } + // TODO: pageable 직접 설정하는 것이 괜찮을까? + Pageable pageable = PageRequest.of(0, 10); + Page postPage = postService.readAllPost(pageable); + assertThat(postPage.getContent()).hasSize(10); + assertThat(postPage.getTotalPages()).isEqualTo(2); + + Pageable pageable2 = PageRequest.of(1, 10); + Page postPage2 = postService.readAllPost(pageable2); + assertThat(postPage2.getContent()).hasSize(5); + } + } + + @Nested + @DisplayName("게시글 단건 조회") + class PostGetOne { + @Test + @DisplayName("정상적으로 특정 게시물 하나를 받아온다.") + void getPostByIdSuccess() { + PostCreateDto postDto = new PostCreateDto(1L, "title", "contents"); + Long savedId = postService.save(postDto); + + PostDetailResponseDto postDetailResponseDto = postService.readPostDetail(savedId); + assertThat(postDetailResponseDto.postId()).isEqualTo(savedId); + } + + @Test + @DisplayName("존재하지 않는 게시물을 호출하여 단건 조회에 실패한다.") + void getPostByIdNotFoundFail() { + assertThatThrownBy(() -> postService.readPostDetail(0L)) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.POST_NOT_FOUND.getMessage()); + } + } + + @Nested + @DisplayName("게시글 수정") + class PostUpdate { + @Test + @DisplayName("정상적으로 PostDto를 받아 글 수정을 완료하는 경우") + void updateSuccessInService() { + PostCreateDto postDto = new PostCreateDto(1L, "test", "test Contents"); + Long savedId = postService.save(postDto); + + String updatedTitle = "test update"; + String updatedContents = "test Contents update"; + PostUpdateDto postUpdateDto = new PostUpdateDto(1L, updatedTitle, updatedContents); + + Long userId = postUpdateDto.userId(); + postService.update(savedId, postUpdateDto, userId); + PostDetailResponseDto postDetailResponseDto = postService.readPostDetail(savedId); + + assertThat(postDetailResponseDto.title()).isEqualTo(updatedTitle); + assertThat(postDetailResponseDto.contents()).isEqualTo(updatedContents); + } + + @Test + @DisplayName("존재하지 않는 게시물을 호출하여 수정에 실패한다.") + void updateByIdNotFoundFail() { + Long userId = 1L; + String updatedTitle = "test update"; + String updatedContents = "test Contents update"; + PostUpdateDto postUpdateDto = new PostUpdateDto(userId, updatedTitle, updatedContents); + assertThatThrownBy(() -> postService.update(0L, postUpdateDto, postUpdateDto.userId())) + .isInstanceOf(BaseException.class).hasMessage(ErrorMessage.POST_NOT_FOUND.getMessage()); + } + + @Test + @DisplayName("제목이 20자 이상인 경우 수정에 실패한다.") + void updateFailByTitleLength() { + // given + PostCreateDto postDto = new PostCreateDto(1L, "test", "test Contents"); + Long savedId = postService.save(postDto); + + PostUpdateDto postUpdateDto = new PostUpdateDto(1L, "testtesttesttesttesttesttest", "test Contents"); + + // when, then + assertThatThrownBy(() -> postService.update(savedId, postUpdateDto, postUpdateDto.userId())) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.WRONG_TITLE_VALUE.getMessage()); + } + + @ParameterizedTest(name = "title이 `{0}`인 경우 수정 로직에서 실패한다.") + @ValueSource(strings = {" ", " "}) + @NullAndEmptySource + @DisplayName("제목이 null이거나 빈 공백인 경우 수정에 실패한다.") + void updateFailByTitleNullOrBlank(String input) { + // given + PostCreateDto postDto = new PostCreateDto(1L, "test", "test Contents"); + Long savedId = postService.save(postDto); + + PostUpdateDto postUpdateDto = new PostUpdateDto(1L, input, "test Contents"); + + // when, then + assertThatThrownBy(() -> postService.update(savedId, postUpdateDto, postUpdateDto.userId())) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.WRONG_TITLE_VALUE.getMessage()); + } + + @ParameterizedTest(name = "contents가 `{0}`인 경우 수정 로직에서 실패한다.") + @ValueSource(strings = {" ", " "}) + @NullAndEmptySource + @DisplayName("내용이 null이거나 빈 공백인 경우 실패한다.") + void updateFailByContents(String input) { + // given + PostCreateDto postDto = new PostCreateDto(1L, "test", "test Contents"); + Long savedId = postService.save(postDto); + + PostUpdateDto postUpdateDto = new PostUpdateDto(1L, "title", input); + + // when, then + assertThatThrownBy(() -> postService.update(savedId, postUpdateDto, postUpdateDto.userId())) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.WRONG_CONTENTS_VALUE.getMessage()); + } + + @Test + @DisplayName("존재하지 않는 유저가 글을 수정하는 경우 예외를 발생시킨다.") + void updateFailWithAnonymousUser() { + // given + PostCreateDto postDto = new PostCreateDto(1L, "test", "test Contents"); + Long savedId = postService.save(postDto); + + PostUpdateDto postUpdateDto = new PostUpdateDto(0L, "title update", "test Contents update"); + + + // when, then + assertThatThrownBy(() -> postService.update(savedId, postUpdateDto, postUpdateDto.userId())) + .isInstanceOf(BaseException.class) + .hasMessage(ErrorMessage.USER_NOT_FOUND.getMessage()); + } + } +}