diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..7ca395fb1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,145 @@ +# Created by https://www.toptal.com/developers/gitignore/api/java,intellij+all,gradle +# Edit at https://www.toptal.com/developers/gitignore?templates=java,intellij+all,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/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* + +### 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/java,intellij+all,gradle \ No newline at end of file diff --git a/HELP.md b/HELP.md new file mode 100644 index 000000000..11290804f --- /dev/null +++ b/HELP.md @@ -0,0 +1,27 @@ +# 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.2/gradle-plugin/reference/html/) +* [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.1.2/gradle-plugin/reference/html/#build-image) +* [Spring Data JPA](https://docs.spring.io/spring-boot/docs/3.1.2/reference/htmlsinge/index.html#data.sql.jpa-and-spring-data) +* [Spring Web](https://docs.spring.io/spring-boot/docs/3.1.2/reference/htmlsinge/index.html#web) + +### Guides + +The following guides illustrate how to use some features concretely: + +* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) +* [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/) + +### 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/build.gradle b/build.gradle new file mode 100644 index 000000000..cc2555676 --- /dev/null +++ b/build.gradle @@ -0,0 +1,78 @@ +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 = 'me.kimihiqq' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +ext { + snippetsDir = file('build/generated-snippets') +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } + asciidoctorExtensions +} + +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.h2database:h2' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + implementation 'org.springframework.boot:spring-boot-starter-validation' + + asciidoctorExtensions 'org.springframework.restdocs:spring-restdocs-asciidoctor' + testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' +} + +tasks.named('test') { + useJUnitPlatform() +} + +test { + outputs.dir snippetsDir + useJUnitPlatform() +} + +asciidoctor { + inputs.dir snippetsDir + configurations 'asciidoctorExtensions' + baseDirFollowsSourceFile() + dependsOn test + outputDir file('src/main/resources/static/docs') +} + + +asciidoctor.doFirst { + delete file('src/main/resources/static/docs') +} + +task copyDocument(type: Copy) { + dependsOn asciidoctor + + from file("build/docs/asciidoc") + into file("src/main/resources/static/docs") +} + +bootJar { + dependsOn copyDocument +} + +build { + dependsOn copyDocument +} 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..6689b85be --- /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..8b9df8d21 --- /dev/null +++ b/src/docs/asciidoc/index.adoc @@ -0,0 +1,67 @@ +:hardbreaks: +ifndef::snippets[] +:snippets: build/generated-snippets +endif::[] + += API Documentation + +This document explains the REST APIs of the application. + +TIP: See the `src/test/java` directory for the actual test cases. + +== HTTP Requests + +This application defines the following as the main, general HTTP requests: + +* POST: To create a resource +* GET: To retrieve a resource +* PUT: To update a resource +* DELETE: To delete a resource + +== 게시판 API + +== 게시글 기능 + +=== Get all posts += {uri-post}/posts + +.Request + +include::{snippets}/get-all-posts/http-request.adoc[] +include::{snippets}/get-all-posts/http-response.adoc[] +include::{snippets}/get-all-posts/response-fields.adoc[] + +=== Get single post += {uri-post}/posts/{id} + +.Request + +include::{snippets}/get-post/http-request.adoc[] +include::{snippets}/get-post/http-response.adoc[] +include::{snippets}/get-post/response-fields.adoc[] + +=== Create new post += {uri-post}/posts + +.Request + +include::{snippets}/create-post/http-request.adoc[] +include::{snippets}/create-post/request-fields.adoc[] + +.Response + +include::{snippets}/create-post/http-response.adoc[] +include::{snippets}/create-post/response-fields.adoc[] + +=== Update a post += {uri-post}/posts/{id} + +.Request + +include::{snippets}/update-post/http-request.adoc[] +include::{snippets}/update-post/request-fields.adoc[] + +.Response + +include::{snippets}/update-post/http-response.adoc[] +include::{snippets}/update-post/response-fields.adoc[] diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/SpringbootBoardJpaApplication.java b/src/main/java/me/kimihiqq/springbootboardjpa/SpringbootBoardJpaApplication.java new file mode 100644 index 000000000..ffeb348d4 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/SpringbootBoardJpaApplication.java @@ -0,0 +1,15 @@ +package me.kimihiqq.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/me/kimihiqq/springbootboardjpa/global/domain/BaseEntity.java b/src/main/java/me/kimihiqq/springbootboardjpa/global/domain/BaseEntity.java new file mode 100644 index 000000000..f60d14820 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/global/domain/BaseEntity.java @@ -0,0 +1,21 @@ +package me.kimihiqq.springbootboardjpa.global.domain; + +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(AuditingEntityListener.class) +@MappedSuperclass +public abstract class BaseEntity { + + @CreatedDate + @Column(name = "created_at", nullable = false, updatable = false) + private LocalDateTime createdAt; + +} diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/global/error/ErrorCode.java b/src/main/java/me/kimihiqq/springbootboardjpa/global/error/ErrorCode.java new file mode 100644 index 000000000..dd2426854 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/global/error/ErrorCode.java @@ -0,0 +1,26 @@ +package me.kimihiqq.springbootboardjpa.global.error; + +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +public enum ErrorCode { + + //User + USER_NOT_FOUND(HttpStatus.NOT_FOUND, "User not found"), + USER_ALREADY_EXISTS(HttpStatus.BAD_REQUEST, "User already exists"), + INVALID_USER_INPUT(HttpStatus.BAD_REQUEST, "Invalid user input"), + + //Post + POST_NOT_FOUND(HttpStatus.NOT_FOUND, "Post not found"), + INVALID_POST_INPUT(HttpStatus.BAD_REQUEST, "Invalid post input"); + + + private final HttpStatus status; + private final String message; + + ErrorCode(HttpStatus status, String message) { + this.status = status; + this.message = message; + } +} \ No newline at end of file diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/global/exception/PostException.java b/src/main/java/me/kimihiqq/springbootboardjpa/global/exception/PostException.java new file mode 100644 index 000000000..2228d0dd9 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/global/exception/PostException.java @@ -0,0 +1,17 @@ +package me.kimihiqq.springbootboardjpa.global.exception; + +import lombok.Getter; +import me.kimihiqq.springbootboardjpa.global.error.ErrorCode; + +@Getter +public class PostException extends RuntimeException { + + private final ErrorCode errorCode; + private final String debugMessage; + + public PostException(ErrorCode errorCode, String debugMessage) { + super(errorCode.getMessage()); + this.errorCode = errorCode; + this.debugMessage = debugMessage; + } +} diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/global/exception/UserException.java b/src/main/java/me/kimihiqq/springbootboardjpa/global/exception/UserException.java new file mode 100644 index 000000000..3b0b1c5e8 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/global/exception/UserException.java @@ -0,0 +1,18 @@ +package me.kimihiqq.springbootboardjpa.global.exception; + +import lombok.Getter; +import me.kimihiqq.springbootboardjpa.global.error.ErrorCode; + +@Getter +public class UserException extends RuntimeException { + + private final ErrorCode errorCode; + private final String debugMessage; + + public UserException(ErrorCode errorCode, String debugMessage) { + super(errorCode.getMessage()); + this.errorCode = errorCode; + this.debugMessage = debugMessage; + } +} + diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/global/exception/handler/GlobalExceptionHandler.java b/src/main/java/me/kimihiqq/springbootboardjpa/global/exception/handler/GlobalExceptionHandler.java new file mode 100644 index 000000000..e987fae8b --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/global/exception/handler/GlobalExceptionHandler.java @@ -0,0 +1,35 @@ +package me.kimihiqq.springbootboardjpa.global.exception.handler; + +import lombok.extern.slf4j.Slf4j; +import me.kimihiqq.springbootboardjpa.global.exception.PostException; +import me.kimihiqq.springbootboardjpa.global.exception.UserException; +import me.kimihiqq.springbootboardjpa.global.exception.response.ErrorResponse; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; + +@Slf4j +@ControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(PostException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity handlePostException(PostException e) { + log.error("PostException Occurred: {}", e.getMessage(), e); + + ErrorResponse errorResponse = new ErrorResponse(e.getErrorCode().getMessage(), e.getDebugMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(UserException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity handleUserException(UserException e) { + log.error("UserException Occurred: {}", e.getMessage(), e); + + ErrorResponse errorResponse = new ErrorResponse(e.getErrorCode().getMessage(), e.getDebugMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); + } +} + diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/global/exception/response/ErrorResponse.java b/src/main/java/me/kimihiqq/springbootboardjpa/global/exception/response/ErrorResponse.java new file mode 100644 index 000000000..c6d483642 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/global/exception/response/ErrorResponse.java @@ -0,0 +1,12 @@ +package me.kimihiqq.springbootboardjpa.global.exception.response; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class ErrorResponse { + private String message; + private String debugMessage; +} + diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/post/controller/PostApiController.java b/src/main/java/me/kimihiqq/springbootboardjpa/post/controller/PostApiController.java new file mode 100644 index 000000000..82b02b4f8 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/post/controller/PostApiController.java @@ -0,0 +1,48 @@ +package me.kimihiqq.springbootboardjpa.post.controller; + +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import me.kimihiqq.springbootboardjpa.post.dto.request.PostCreateRequest; +import me.kimihiqq.springbootboardjpa.post.dto.request.PostUpdateRequest; +import me.kimihiqq.springbootboardjpa.post.dto.response.PostResponse; +import me.kimihiqq.springbootboardjpa.post.service.PostService; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/api/v1/posts") +@RequiredArgsConstructor +public class PostApiController { + + private final PostService postService; + + @GetMapping + public ResponseEntity> getPosts(@PageableDefault(sort = "id", size = 10, direction = Sort.Direction.DESC) Pageable pageable) { + Page responseDto = postService.getPosts(pageable); + return ResponseEntity.ok().body(responseDto); + } + + @GetMapping("/{id}") + public ResponseEntity getPost(@PathVariable Long id) { + PostResponse responseDto = postService.getPost(id); + return ResponseEntity.ok().body(responseDto); + } + + @PostMapping + public ResponseEntity createPost(@RequestBody @Valid PostCreateRequest requestDto) { + PostResponse reponse = postService.save(requestDto); + return ResponseEntity.ok().body(reponse); + } + + + @PutMapping("/{id}") + public ResponseEntity updatePost(@PathVariable Long id, @RequestBody @Valid PostUpdateRequest requestDto) { + PostResponse reponse = postService.update(id, requestDto); + return ResponseEntity.ok().body(reponse); + } +} + diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/post/domain/Post.java b/src/main/java/me/kimihiqq/springbootboardjpa/post/domain/Post.java new file mode 100644 index 000000000..b338ac66b --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/post/domain/Post.java @@ -0,0 +1,64 @@ +package me.kimihiqq.springbootboardjpa.post.domain; + +import jakarta.persistence.*; +import lombok.*; +import me.kimihiqq.springbootboardjpa.global.domain.BaseEntity; +import me.kimihiqq.springbootboardjpa.global.error.ErrorCode; +import me.kimihiqq.springbootboardjpa.global.exception.PostException; +import me.kimihiqq.springbootboardjpa.user.domain.User; + +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Getter +@Entity +public class Post extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Column(nullable = false, length = 50) + private String title; + + @Column(nullable = false) + private String content; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + @Builder + public Post(String title, String content, User user) { + validateTitle(title); + validateContent(content); + this.title = title; + this.content = content; + setUser(user); + } + + public void setUser(User user) { + if (this.user != null) { + this.user.getPosts().remove(this); + } + this.user = user; + user.getPosts().add(this); + } + + private void validateTitle(String title) { + if (title == null || title.isBlank()) { + throw new PostException(ErrorCode.INVALID_POST_INPUT, String.format("Invalid title: %s", title)); + } + } + + private void validateContent(String content) { + if (content == null || content.isBlank()) { + throw new PostException(ErrorCode.INVALID_POST_INPUT, String.format("Invalid content: %s", content)); + } + } + + public void updatePost(String title, String content) { + validateTitle(title); + validateContent(content); + this.title = title; + this.content = content; + } +} \ No newline at end of file diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/post/dto/request/PostCreateRequest.java b/src/main/java/me/kimihiqq/springbootboardjpa/post/dto/request/PostCreateRequest.java new file mode 100644 index 000000000..5413c49de --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/post/dto/request/PostCreateRequest.java @@ -0,0 +1,29 @@ +package me.kimihiqq.springbootboardjpa.post.dto.request; + +import jakarta.validation.constraints.NotEmpty; +import lombok.*; +import me.kimihiqq.springbootboardjpa.post.domain.Post; +import me.kimihiqq.springbootboardjpa.user.domain.User; + +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +@Getter +@ToString +public class PostCreateRequest { + + @NotEmpty + private String title; + + @NotEmpty + private String content; + private Long userId; + + public Post toEntity(User user) { + return Post.builder() + .title(title) + .content(content) + .user(user) + .build(); + } +} + diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/post/dto/request/PostUpdateRequest.java b/src/main/java/me/kimihiqq/springbootboardjpa/post/dto/request/PostUpdateRequest.java new file mode 100644 index 000000000..909c90024 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/post/dto/request/PostUpdateRequest.java @@ -0,0 +1,20 @@ +package me.kimihiqq.springbootboardjpa.post.dto.request; + +import jakarta.validation.constraints.NotEmpty; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +@Getter +public class PostUpdateRequest { + + @NotEmpty + private String title; + + @NotEmpty + private String content; +} + diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/post/dto/response/PostResponse.java b/src/main/java/me/kimihiqq/springbootboardjpa/post/dto/response/PostResponse.java new file mode 100644 index 000000000..918dd8da8 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/post/dto/response/PostResponse.java @@ -0,0 +1,23 @@ +package me.kimihiqq.springbootboardjpa.post.dto.response; + +import lombok.Getter; +import me.kimihiqq.springbootboardjpa.post.domain.Post; + +import java.time.LocalDateTime; + +@Getter +public class PostResponse { + private final Long id; + private final String title; + private final String content; + private final Long userId; + private final LocalDateTime createdAt; + + public PostResponse(Post post) { + this.id = post.getId(); + this.title = post.getTitle(); + this.content = post.getContent(); + this.userId = post.getUser().getId(); + this.createdAt = post.getCreatedAt(); + } +} diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/post/repository/PostRepository.java b/src/main/java/me/kimihiqq/springbootboardjpa/post/repository/PostRepository.java new file mode 100644 index 000000000..9ad9e1451 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/post/repository/PostRepository.java @@ -0,0 +1,9 @@ +package me.kimihiqq.springbootboardjpa.post.repository; + +import me.kimihiqq.springbootboardjpa.post.domain.Post; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PostRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/post/service/PostService.java b/src/main/java/me/kimihiqq/springbootboardjpa/post/service/PostService.java new file mode 100644 index 000000000..a31e968d4 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/post/service/PostService.java @@ -0,0 +1,49 @@ +package me.kimihiqq.springbootboardjpa.post.service; + +import org.springframework.transaction.annotation.Transactional; +import lombok.RequiredArgsConstructor; +import me.kimihiqq.springbootboardjpa.post.domain.Post; +import me.kimihiqq.springbootboardjpa.post.dto.request.PostCreateRequest; +import me.kimihiqq.springbootboardjpa.post.dto.request.PostUpdateRequest; +import me.kimihiqq.springbootboardjpa.post.dto.response.PostResponse; +import me.kimihiqq.springbootboardjpa.post.repository.PostRepository; +import me.kimihiqq.springbootboardjpa.user.domain.User; +import me.kimihiqq.springbootboardjpa.user.repository.UserRepository; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@RequiredArgsConstructor +@Service +public class PostService { + + private final PostRepository postRepository; + private final UserRepository userRepository; + + public Page getPosts(Pageable pageable) { + return postRepository.findAll(pageable).map(PostResponse::new); + } + + public PostResponse getPost(Long id) { + Post post = postRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id)); + return new PostResponse(post); + } + + @Transactional + public PostResponse save(PostCreateRequest requestDto) { + User user = userRepository.findById(requestDto.getUserId()) + .orElseThrow(() -> new IllegalArgumentException("해당 사용자가 없습니다. id=" + requestDto.getUserId())); + Post post = requestDto.toEntity(user); + post = postRepository.save(post); + return new PostResponse(post); + } + + @Transactional + public PostResponse update(Long id, PostUpdateRequest requestDto) { + Post post = postRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id)); + post.updatePost(requestDto.getTitle(), requestDto.getContent()); + return new PostResponse(post); + } +} diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/user/domain/User.java b/src/main/java/me/kimihiqq/springbootboardjpa/user/domain/User.java new file mode 100644 index 000000000..13374ae6e --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/user/domain/User.java @@ -0,0 +1,75 @@ +package me.kimihiqq.springbootboardjpa.user.domain; + +import jakarta.persistence.*; +import lombok.*; +import me.kimihiqq.springbootboardjpa.global.domain.BaseEntity; +import me.kimihiqq.springbootboardjpa.global.error.ErrorCode; +import me.kimihiqq.springbootboardjpa.global.exception.UserException; +import me.kimihiqq.springbootboardjpa.post.domain.Post; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + + +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Table(name = "users") +@Getter +@Entity +public class User extends BaseEntity { + + private static final Pattern NAME_PATTERN = Pattern.compile("[\\p{L} ]+"); + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Column(nullable = false) + private String name; + + @Column(nullable = false) + private int age; + + private String hobby; + + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) + private List posts = new ArrayList<>(); + + @Builder + public User(String name, int age, String hobby) { + validateAge(age); + validateName(name); + this.name = name; + this.age = age; + this.hobby = hobby; + } + + + private void validateName(String name) { + if (name == null || name.isBlank() || !NAME_PATTERN.matcher(name).matches()) { + throw new UserException(ErrorCode.INVALID_USER_INPUT, String.format("Invalid name: %s", name)); + } + } + + private void validateAge(int age) { + if (age < 0 || age > 120) { + throw new UserException(ErrorCode.INVALID_USER_INPUT, String.format("Invalid age: %d", age)); + } + } + + public void addPost(Post post) { + post.setUser(this); + } + + public void removePost(Post post) { + post.setUser(null); + } + + public void updateUser(String name, int age, String hobby) { + validateName(name); + validateAge(age); + this.name = name; + this.age = age; + this.hobby = hobby; + } +} \ No newline at end of file diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/user/dto/UserCreateRequest.java b/src/main/java/me/kimihiqq/springbootboardjpa/user/dto/UserCreateRequest.java new file mode 100644 index 000000000..8dabfbb10 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/user/dto/UserCreateRequest.java @@ -0,0 +1,31 @@ +package me.kimihiqq.springbootboardjpa.user.dto; + +import jakarta.validation.constraints.NotEmpty; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import me.kimihiqq.springbootboardjpa.user.domain.User; + +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +@Getter +public class UserCreateRequest { + + @NotEmpty + private String name; + + @NotEmpty + private int age; + + @NotEmpty + private String hobby; + + public User toEntity() { + return User.builder() + .name(name) + .age(age) + .hobby(hobby) + .build(); + } +} diff --git a/src/main/java/me/kimihiqq/springbootboardjpa/user/repository/UserRepository.java b/src/main/java/me/kimihiqq/springbootboardjpa/user/repository/UserRepository.java new file mode 100644 index 000000000..4ed180296 --- /dev/null +++ b/src/main/java/me/kimihiqq/springbootboardjpa/user/repository/UserRepository.java @@ -0,0 +1,14 @@ +package me.kimihiqq.springbootboardjpa.user.repository; + + +import me.kimihiqq.springbootboardjpa.user.domain.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends JpaRepository { +} + + + + diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 000000000..ccc39dc9f --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,2 @@ + +spring.datasource.initialization-mode=never diff --git a/src/test/java/me/kimihiqq/springbootboardjpa/SpringbootBoardJpaApplicationTests.java b/src/test/java/me/kimihiqq/springbootboardjpa/SpringbootBoardJpaApplicationTests.java new file mode 100644 index 000000000..bed012848 --- /dev/null +++ b/src/test/java/me/kimihiqq/springbootboardjpa/SpringbootBoardJpaApplicationTests.java @@ -0,0 +1,13 @@ +package me.kimihiqq.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/me/kimihiqq/springbootboardjpa/post/controller/PostApiControllerTest.java b/src/test/java/me/kimihiqq/springbootboardjpa/post/controller/PostApiControllerTest.java new file mode 100644 index 000000000..d0e0ca693 --- /dev/null +++ b/src/test/java/me/kimihiqq/springbootboardjpa/post/controller/PostApiControllerTest.java @@ -0,0 +1,199 @@ +package me.kimihiqq.springbootboardjpa.post.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.transaction.Transactional; +import me.kimihiqq.springbootboardjpa.post.domain.Post; +import me.kimihiqq.springbootboardjpa.post.dto.request.PostCreateRequest; +import me.kimihiqq.springbootboardjpa.post.dto.request.PostUpdateRequest; +import me.kimihiqq.springbootboardjpa.post.repository.PostRepository; +import me.kimihiqq.springbootboardjpa.user.domain.User; +import me.kimihiqq.springbootboardjpa.user.dto.UserCreateRequest; +import me.kimihiqq.springbootboardjpa.user.repository.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.restdocs.payload.JsonFieldType; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; +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.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@AutoConfigureMockMvc +@AutoConfigureRestDocs +@SpringBootTest +@Transactional +class PostApiControllerTest { + + @Autowired + MockMvc mockMvc; + + @Autowired + ObjectMapper objectMapper; + + @Autowired + PostRepository postRepository; + + @Autowired + UserRepository userRepository; + + User user; + + @BeforeEach + void setUp() { + User temp = new UserCreateRequest("you", 40, "play").toEntity(); + user = userRepository.save(temp); + } + + @Test + @DisplayName("Get all posts") + public void getPostsTest() throws Exception { + + for (int i = 0; i < 5; i++) { + Post post = Post.builder() + .title("Test title " + i) + .content("Test content " + i) + .user(user) + .build(); + postRepository.save(post); + } + + mockMvc.perform(get("/api/v1/posts")) + .andExpect(status().isOk()) + .andDo(print()) + .andDo(document("get-all-posts", + preprocessResponse(prettyPrint()), + responseFields( + fieldWithPath("content[].id").type(JsonFieldType.NUMBER).description("Post Id"), + fieldWithPath("content[].title").type(JsonFieldType.STRING).description("Post Title"), + fieldWithPath("content[].content").type(JsonFieldType.STRING).description("Post Content"), + fieldWithPath("content[].userId").type(JsonFieldType.NUMBER).description("Post User Id"), + fieldWithPath("content[].createdAt").type(JsonFieldType.STRING).description("Post Created At"), + fieldWithPath("pageable.sort.empty").type(JsonFieldType.BOOLEAN).description("Sort Empty"), + fieldWithPath("pageable.sort.sorted").type(JsonFieldType.BOOLEAN).description("Sorted"), + fieldWithPath("pageable.sort.unsorted").type(JsonFieldType.BOOLEAN).description("Unsorted"), + fieldWithPath("pageable.offset").type(JsonFieldType.NUMBER).description("Offset"), + fieldWithPath("pageable.pageNumber").type(JsonFieldType.NUMBER).description("Page Number"), + fieldWithPath("pageable.pageSize").type(JsonFieldType.NUMBER).description("Page Size"), + fieldWithPath("pageable.paged").type(JsonFieldType.BOOLEAN).description("Paged"), + fieldWithPath("pageable.unpaged").type(JsonFieldType.BOOLEAN).description("Unpaged"), + fieldWithPath("last").type(JsonFieldType.BOOLEAN).description("Last"), + fieldWithPath("totalPages").type(JsonFieldType.NUMBER).description("Total Pages"), + fieldWithPath("totalElements").type(JsonFieldType.NUMBER).description("Total Elements"), + fieldWithPath("size").type(JsonFieldType.NUMBER).description("Size"), + fieldWithPath("number").type(JsonFieldType.NUMBER).description("Number"), + fieldWithPath("sort.empty").type(JsonFieldType.BOOLEAN).description("Sort Empty"), + fieldWithPath("sort.sorted").type(JsonFieldType.BOOLEAN).description("Sorted"), + fieldWithPath("sort.unsorted").type(JsonFieldType.BOOLEAN).description("Unsorted"), + fieldWithPath("numberOfElements").type(JsonFieldType.NUMBER).description("Number of Elements"), + fieldWithPath("first").type(JsonFieldType.BOOLEAN).description("First"), + fieldWithPath("empty").type(JsonFieldType.BOOLEAN).description("Empty") + ) + )); + } + + @Test + @DisplayName("Get single post") + public void getPostTest() throws Exception { + Post post = Post.builder() + .title("Test title") + .content("Test content") + .user(user) + .build(); + postRepository.save(post); + + mockMvc.perform(get("/api/v1/posts/{id}", post.getId())) + .andExpect(status().isOk()) + .andDo(print()) + .andDo(document("get-post", + preprocessResponse(prettyPrint()), + pathParameters( + parameterWithName("id").description("Post ID") + ), + responseFields( + fieldWithPath("id").type(JsonFieldType.NUMBER).description("Post Id"), + fieldWithPath("title").type(JsonFieldType.STRING).description("Post Title"), + fieldWithPath("content").type(JsonFieldType.STRING).description("Post Content"), + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("User Id"), + fieldWithPath("createdAt").type(JsonFieldType.STRING).description("Post createdAt") + ) + )); + } + + @Test + @DisplayName("Create new post") + public void createPostTest() throws Exception { + + PostCreateRequest requestDto = new PostCreateRequest(" Test title", "Test content", user.getId()); + + mockMvc.perform(post("/api/v1/posts") + .contentType(APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestDto))) + .andExpect(status().isOk()) + .andDo(print()) + .andDo(document("create-post", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + requestFields( + fieldWithPath("title").type(JsonFieldType.STRING).description("Post Title"), + fieldWithPath("content").type(JsonFieldType.STRING).description("Post Content"), + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("User Id") + ), + responseFields( + fieldWithPath("id").type(JsonFieldType.NUMBER).description("Post Id"), + fieldWithPath("title").type(JsonFieldType.STRING).description("Post Title"), + fieldWithPath("content").type(JsonFieldType.STRING).description("Post Content"), + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("User Id"), + fieldWithPath("createdAt").type(JsonFieldType.STRING).description("Post createdAt") + ) + )); + } + + @Test + @DisplayName("Update a post") + public void updatePostTest() throws Exception { + + Post post = Post.builder() + .title("Test title") + .content("Test content") + .user(user) + .build(); + postRepository.save(post); + + PostUpdateRequest requestDto = new PostUpdateRequest("Updated title", "Updated content"); + + mockMvc.perform(put("/api/v1/posts/{id}", post.getId()) + .contentType(APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestDto))) + .andExpect(status().isOk()) + .andDo(print()) + .andDo(document("update-post", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + pathParameters( + parameterWithName("id").description("Post ID") + ), + requestFields( + fieldWithPath("title").type(JsonFieldType.STRING).description("New Post Title"), + fieldWithPath("content").type(JsonFieldType.STRING).description("New Post Content") + ), + responseFields( + fieldWithPath("id").type(JsonFieldType.NUMBER).description("Post Id"), + fieldWithPath("title").type(JsonFieldType.STRING).description("Post Title"), + fieldWithPath("content").type(JsonFieldType.STRING).description("Post Content"), + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("User Id"), + fieldWithPath("createdAt").type(JsonFieldType.STRING).description("Post createdAt") + ) + )); + } +}