diff --git a/board/.gitignore b/board/.gitignore new file mode 100644 index 000000000..4ddc2e315 --- /dev/null +++ b/board/.gitignore @@ -0,0 +1,43 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +.gradle/ +.idea/ +build/ +gradle/ +logs/ \ No newline at end of file diff --git a/board/build.gradle b/board/build.gradle new file mode 100644 index 000000000..21b063a13 --- /dev/null +++ b/board/build.gradle @@ -0,0 +1,83 @@ +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' + asciidoctorExt 'org.springframework.restdocs:spring-restdocs-asciidoctor' + testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' + implementation 'org.springframework.boot:spring-boot-starter-validation' +} + +ext { + snippetsDir = file('build/generated-snippets') +} + +asciidoctor { + inputs.dir snippetsDir + configurations 'asciidoctorExt' + dependsOn test +} + +asciidoctor.doFirst { + delete file("src/main/resources/static/docs") +} + +bootJar { + dependsOn asciidoctor + from("${asciidoctor.outputDir}/html5") { + into 'static/docs' + } +} + +task copyDocument(type: Copy) { + dependsOn asciidoctor + from file("$buildDir/docs/asciidoc") + into file("src/main/resources/static/docs") +} + +build { + dependsOn copyDocument +} + +test { + useJUnitPlatform() + outputs.dir snippetsDir +} + + + +tasks.named('bootBuildImage') { + builder = 'paketobuildpacks/builder-jammy-base:latest' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/board/docker-compose.yml b/board/docker-compose.yml new file mode 100644 index 000000000..4aab5e023 --- /dev/null +++ b/board/docker-compose.yml @@ -0,0 +1,13 @@ +version: '3' + +services: + mysql: + image: mysql:latest + container_name: board + environment: + MYSQL_ROOT_PASSWORD: + MYSQL_DATABASE: board + MYSQL_CHARSET: utf8mb4 + MYSQL_COLLATION: utf8mb4_unicode_ci + ports: + - "3307:3306" diff --git a/board/gradle/wrapper/gradle-wrapper.jar b/board/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..7f93135c4 Binary files /dev/null and b/board/gradle/wrapper/gradle-wrapper.jar differ diff --git a/board/gradle/wrapper/gradle-wrapper.properties b/board/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..3fa8f862f --- /dev/null +++ b/board/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/board/gradlew b/board/gradlew new file mode 100644 index 000000000..1aa94a426 --- /dev/null +++ b/board/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/board/gradlew.bat b/board/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/board/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/board/settings.gradle b/board/settings.gradle new file mode 100644 index 000000000..5f717a7cc --- /dev/null +++ b/board/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'board' diff --git a/board/src/docs/asciidoc/index.adoc b/board/src/docs/asciidoc/index.adoc new file mode 100644 index 000000000..fd3f2e5a2 --- /dev/null +++ b/board/src/docs/asciidoc/index.adoc @@ -0,0 +1,51 @@ +:hardbreaks: +ifndef::snippets[] +:snippets: ../../../build/generated-snippets +endif::[] + +== 게시글 + +=== 게시글 등록 + +=== /api/v1/posts + +.Request +include::{snippets}/post-save/http-request.adoc[] +include::{snippets}/post-save/request-fields.adoc[] + +.Response +include::{snippets}/post-save/http-response.adoc[] +include::{snippets}/post-save/response-fields.adoc[] + +=== 게시글 조회 + +=== /api/v1/posts + +.Request +include::{snippets}/post-findAll/http-request.adoc[] + +.Response +include::{snippets}/post-findAll/http-response.adoc[] +include::{snippets}/post-findAll/response-fields.adoc[] + +=== 게시글 ID로 조회 + +=== /api/v1/posts/{id} + +.Request +include::{snippets}/post-findById/http-request.adoc[] + +.Response +include::{snippets}/post-findById/http-response.adoc[] +include::{snippets}/post-findById/response-fields.adoc[] + +=== 게시글 수정 + +=== /api/v1/posts/{id} + +.Request +include::{snippets}/post-update/http-request.adoc[] +include::{snippets}/post-update/request-fields.adoc[] + +.Response +include::{snippets}/post-update/http-response.adoc[] \ No newline at end of file diff --git a/board/src/docs/asciidoc/index.html b/board/src/docs/asciidoc/index.html new file mode 100644 index 000000000..6b26dfe2d --- /dev/null +++ b/board/src/docs/asciidoc/index.html @@ -0,0 +1,897 @@ + + + + + + + +게시글 + + + + + +
+
+

게시글

+
+
+

게시글 등록

+ +
+
+

/api/v1/posts

+
+
Request
+
+
POST /api/posts HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Content-Length: 48
+Host: localhost:8080
+
+{"userId":1,"title":"title","content":"content"}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

userId

Number

작성자 ID

title

String

게시글 제목

content

String

게시글 내용

+
+
Response
+
+
HTTP/1.1 201 Created
+Content-Type: application/json
+Content-Length: 161
+
+{"resultCode":"S01","msg":"성공","data":{"userId":1,"title":"title","content":"content","createdAt":"2023-11-20T23:49:20.0561503"},"fail":false,"success":true}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

resultCode

String

결과코드

success

Boolean

성공여부

fail

Boolean

실패여부

msg

String

결과메시지

data

Object

응답데이터

data.userId

Number

작성자 ID

data.title

String

게시글 제목

data.content

String

게시글 내용

data.createdAt

String

게시글 생성 시간

+
+
+

게시글 조회

+ +
+
+

/api/v1/posts

+
+
Request
+
+
GET /api/posts HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Host: localhost:8080
+
+
+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 477
+
+{"resultCode":"S01","msg":"성공","data":{"content":[{"userId":1,"title":"title","content":"content","createdAt":"2023-11-20T23:49:20.7001539"}],"pageable":{"pageNumber":0,"pageSize":10,"sort":{"empty":true,"sorted":false,"unsorted":true},"offset":0,"unpaged":false,"paged":true},"last":true,"totalPages":1,"totalElements":1,"size":10,"number":0,"sort":{"empty":true,"sorted":false,"unsorted":true},"first":true,"numberOfElements":1,"empty":false},"fail":false,"success":true}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

resultCode

String

결과코드

success

Boolean

성공여부

fail

Boolean

실패여부

msg

String

결과메시지

data.content[].userId

Number

작성자 ID

data.content[].title

String

게시글 제목

data.content[].content

String

게시글 내용

data.content[].createdAt

String

게시글 생성 시간

data.pageable.pageNumber

Number

페이지 번호

data.pageable.pageSize

Number

페이지 개수

data.pageable.sort.empty

Boolean

공백 여부

data.pageable.sort.sorted

Boolean

정렬 O

data.pageable.sort.unsorted

Boolean

정렬 X

data.pageable.offset

Number

오프셋

data.pageable.paged

Boolean

페이지 O

data.pageable.unpaged

Boolean

페이지 X

data.last

Boolean

마지막 여부

data.totalPages

Number

전체 페이지

data.totalElements

Number

전체 데이터 개수

data.first

Boolean

처음 여부

data.size

Number

크기

data.number

Number

번호

data.sort.empty

Boolean

정렬 공백 여부

data.sort.sorted

Boolean

정렬 여부(O)

data.sort.unsorted

Boolean

정렬 여부(X)

data.numberOfElements

Number

데이터 개수

data.empty

Boolean

공백 여부

+
+
+

게시글 ID로 조회

+ +
+
+

/api/v1/posts/{id}

+
+
Request
+
+
GET /api/posts/1 HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Host: localhost:8080
+
+
+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 161
+
+{"resultCode":"S01","msg":"성공","data":{"userId":1,"title":"title","content":"content","createdAt":"2023-11-20T23:49:20.8321529"},"fail":false,"success":true}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

resultCode

String

결과코드

success

Boolean

성공여부

fail

Boolean

실패여부

msg

String

결과메시지

data

Object

응답데이터

data.userId

Number

작성자 ID

data.title

String

게시글 제목

data.content

String

게시글 내용

data.createdAt

String

게시글 생성 시간

+
+
+

게시글 수정

+ +
+
+

/api/v1/posts/{id}

+
+
Request
+
+
POST /api/posts/1 HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Content-Length: 48
+Host: localhost:8080
+
+{"userId":1,"title":"title","content":"content"}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

userId

Number

작성자 ID

title

String

게시글 제목

content

String

게시글 내용

+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 75
+
+{"resultCode":"S01","msg":"성공","data":null,"fail":false,"success":true}
+
+
+
+
+
+
+ + + \ No newline at end of file diff --git a/board/src/main/java/com/example/board/BoardApplication.java b/board/src/main/java/com/example/board/BoardApplication.java new file mode 100644 index 000000000..0e2ce6640 --- /dev/null +++ b/board/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; + +@SpringBootApplication +@EnableJpaAuditing +public class BoardApplication { + + public static void main(String[] args) { + SpringApplication.run(BoardApplication.class, args); + } + +} diff --git a/board/src/main/java/com/example/board/controller/PostRestController.java b/board/src/main/java/com/example/board/controller/PostRestController.java new file mode 100644 index 000000000..dc7533c59 --- /dev/null +++ b/board/src/main/java/com/example/board/controller/PostRestController.java @@ -0,0 +1,45 @@ +package com.example.board.controller; +import com.example.board.dto.ApiResult; +import com.example.board.dto.PostDto; +import com.example.board.service.PostService; +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.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/posts") +public class PostRestController { + + private final PostService service; + + @GetMapping + public ApiResult> findAll(@PageableDefault(page=0,size = 10) Pageable pageable) { + Page responses = service.findAll(pageable); + return ApiResult.successOf(responses); + } + + @GetMapping("/{postId}") + public ApiResult findById(@PathVariable Long postId) { + PostDto.Response response = service.findById(postId); + return ApiResult.successOf(response); + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public ApiResult save(@Validated @RequestBody PostDto.Request request) { + PostDto.Response response = service.save(request); + return ApiResult.successOf(response); + } + + @PostMapping("/{postId}") + public ApiResult update(@PathVariable Long postId, + @Validated @RequestBody PostDto.Request request) { + service.update(postId, request); + return ApiResult.successOf(); + } +} diff --git a/board/src/main/java/com/example/board/controller/UserRestController.java b/board/src/main/java/com/example/board/controller/UserRestController.java new file mode 100644 index 000000000..d21638d9a --- /dev/null +++ b/board/src/main/java/com/example/board/controller/UserRestController.java @@ -0,0 +1,44 @@ +package com.example.board.controller; + +import com.example.board.dto.ApiResult; +import com.example.board.service.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +import static com.example.board.dto.UserDto.Request; +import static com.example.board.dto.UserDto.Response; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/users") +public class UserRestController { + private final UserService service; + + @GetMapping + public ApiResult> findAll() { + List responses = service.findAll(); + return ApiResult.successOf(responses); + } + + @GetMapping("/{userId}") + public ApiResult findById(@PathVariable Long userId) { + Response response = service.findById(userId); + return ApiResult.successOf(response); + } + + @PostMapping + public ApiResult save(@Validated @RequestBody Request request) { + Response response = service.save(request); + return ApiResult.successOf(response); + } + + @PostMapping("/{userId}") + public ApiResult update(@PathVariable Long userId, + @Validated @RequestBody Request request) { + service.update(userId, request); + return ApiResult.successOf(); + } +} diff --git a/board/src/main/java/com/example/board/domain/Post.java b/board/src/main/java/com/example/board/domain/Post.java new file mode 100644 index 000000000..3f03482ea --- /dev/null +++ b/board/src/main/java/com/example/board/domain/Post.java @@ -0,0 +1,43 @@ +package com.example.board.domain; + +import com.example.board.dto.PostDto; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@Entity +@Getter +@EntityListeners(AuditingEntityListener.class) +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class Post { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String title; + + @Lob + private String content; + + @CreatedDate + private LocalDateTime createdAt; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + + + public void changePost(String title, String content) { + this.title = title; + this.content = content; + } +} diff --git a/board/src/main/java/com/example/board/domain/User.java b/board/src/main/java/com/example/board/domain/User.java new file mode 100644 index 000000000..bb9f9f1d6 --- /dev/null +++ b/board/src/main/java/com/example/board/domain/User.java @@ -0,0 +1,39 @@ +package com.example.board.domain; + +import com.example.board.dto.UserDto; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@Entity +@Getter +@EntityListeners(AuditingEntityListener.class) +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + private int age; + private String hobby; + + @CreatedDate + private LocalDateTime createdAt; + + + + public void changeUserInfo(String name, int age, String hobby) { + this.name = name; + this.age = age; + this.hobby = hobby; + } +} diff --git a/board/src/main/java/com/example/board/dto/ApiResult.java b/board/src/main/java/com/example/board/dto/ApiResult.java new file mode 100644 index 000000000..f91824d79 --- /dev/null +++ b/board/src/main/java/com/example/board/dto/ApiResult.java @@ -0,0 +1,40 @@ +package com.example.board.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class ApiResult { + private String resultCode; + private String msg; + private T data; + + public static ApiResult of(String resultCode, String msg, T data) { + return new ApiResult<>(resultCode, msg, data); + } + + public static ApiResult of(String resultCode, String msg) { + return of(resultCode, msg, null); + } + + public static ApiResult successOf(T data) { + return of("S01", "성공", data); + } + + public static ApiResult successOf() { + return of("S01", "성공", null); + } + + public static ApiResult failOf(T data) { + return of("F01", "실패", data); + } + + public boolean isSuccess() { + return resultCode.startsWith("S01"); + } + + public boolean isFail() { + return !isSuccess(); + } +} diff --git a/board/src/main/java/com/example/board/dto/PostDto.java b/board/src/main/java/com/example/board/dto/PostDto.java new file mode 100644 index 000000000..8e8ed8183 --- /dev/null +++ b/board/src/main/java/com/example/board/dto/PostDto.java @@ -0,0 +1,33 @@ +package com.example.board.dto; + +import com.example.board.domain.Post; +import com.example.board.domain.User; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import lombok.Builder; + +import java.time.LocalDateTime; + +public class PostDto { + @Builder + public record Request(@NotNull Long userId, @NotEmpty(message = "제목 없음") String title, @NotEmpty String content) {} + + @Builder + public record Response(Long userId, String title, String content, LocalDateTime createdAt) {} + + public static Post toEntity(User user, PostDto.Request request) { + return Post.builder() + .title(request.title()) + .content(request.content()) + .user(user) + .build(); + } + public static Response toResponse(Post post) { + return Response.builder() + .userId(post.getUser().getId()) + .title(post.getTitle()) + .content(post.getContent()) + .createdAt(post.getCreatedAt()) + .build(); + } +} diff --git a/board/src/main/java/com/example/board/dto/UserDto.java b/board/src/main/java/com/example/board/dto/UserDto.java new file mode 100644 index 000000000..3e961a624 --- /dev/null +++ b/board/src/main/java/com/example/board/dto/UserDto.java @@ -0,0 +1,29 @@ +package com.example.board.dto; + +import com.example.board.domain.User; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import lombok.Builder; + +public class UserDto { + @Builder + public record Request(@NotEmpty String name, @NotNull Integer age, @NotEmpty String hobby) {} + + @Builder + public record Response(Long userId, String name, int age, String hobby) {} + public static User toEntity(UserDto.Request request) { + return User.builder() + .name(request.name()) + .age(request.age()) + .hobby(request.hobby()) + .build(); + } + public static UserDto.Response toResponse(User user) { + return Response.builder() + .userId(user.getId()) + .name(user.getName()) + .age(user.getAge()) + .hobby(user.getHobby()) + .build(); + } +} diff --git a/board/src/main/java/com/example/board/exception/GlobalHandlerException.java b/board/src/main/java/com/example/board/exception/GlobalHandlerException.java new file mode 100644 index 000000000..f8365cb48 --- /dev/null +++ b/board/src/main/java/com/example/board/exception/GlobalHandlerException.java @@ -0,0 +1,33 @@ +package com.example.board.exception; + +import com.example.board.dto.ApiResult; +import org.springframework.http.HttpStatus; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.NoSuchElementException; + +@RestControllerAdvice +public class GlobalHandlerException { + + @ExceptionHandler(NoSuchElementException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public ApiResult noSuchElement() { + return ApiResult.failOf("존재하지 않는 정보입니다."); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + ApiResult handlerArgumentException() { + return ApiResult.failOf("값을 잘못 입력하셨습니다."); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + ApiResult emptyTitleException(MethodArgumentNotValidException e) { + return ApiResult.failOf(e.getMessage()); + } +} \ No newline at end of file diff --git a/board/src/main/java/com/example/board/repository/PostRepository.java b/board/src/main/java/com/example/board/repository/PostRepository.java new file mode 100644 index 000000000..fe46a1369 --- /dev/null +++ b/board/src/main/java/com/example/board/repository/PostRepository.java @@ -0,0 +1,11 @@ +package com.example.board.repository; + +import com.example.board.domain.Post; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PostRepository extends JpaRepository { + + public Page findAll(Pageable pageable); +} diff --git a/board/src/main/java/com/example/board/repository/UserRepository.java b/board/src/main/java/com/example/board/repository/UserRepository.java new file mode 100644 index 000000000..ffdbc3678 --- /dev/null +++ b/board/src/main/java/com/example/board/repository/UserRepository.java @@ -0,0 +1,7 @@ +package com.example.board.repository; + +import com.example.board.domain.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} diff --git a/board/src/main/java/com/example/board/service/PostService.java b/board/src/main/java/com/example/board/service/PostService.java new file mode 100644 index 000000000..9f5c5b9d4 --- /dev/null +++ b/board/src/main/java/com/example/board/service/PostService.java @@ -0,0 +1,48 @@ +package com.example.board.service; + +import com.example.board.domain.Post; +import com.example.board.domain.User; +import com.example.board.dto.PostDto; +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; + +import java.util.NoSuchElementException; + +import static com.example.board.dto.PostDto.*; + +@RequiredArgsConstructor +@Service +@Transactional +public class PostService { + + private final PostRepository postRepository; + private final UserRepository userRepository; + + public Response save(Request request) { + User user = userRepository.findById(request.userId()).orElseThrow(NoSuchElementException::new); + Post post = PostDto.toEntity(user, request); + return toResponse(postRepository.save(post)); + } + + @Transactional(readOnly = true) + public Page findAll(Pageable pageable) { + Page posts = postRepository.findAll(pageable); + return posts.map(PostDto::toResponse); + } + + @Transactional(readOnly = true) + public Response findById(Long id) { + Post post = postRepository.findById(id).orElseThrow(NoSuchElementException::new); + return toResponse(post); + } + + public void update(Long postId, Request request) { + Post post = postRepository.findById(postId).orElseThrow(NoSuchElementException::new); + post.changePost(request.title(), request.content()); + } +} diff --git a/board/src/main/java/com/example/board/service/UserService.java b/board/src/main/java/com/example/board/service/UserService.java new file mode 100644 index 000000000..0b14fd9f1 --- /dev/null +++ b/board/src/main/java/com/example/board/service/UserService.java @@ -0,0 +1,40 @@ +package com.example.board.service; + +import com.example.board.domain.User; +import com.example.board.dto.UserDto; +import com.example.board.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.NoSuchElementException; + +@RequiredArgsConstructor +@Service +@Transactional +public class UserService { + private final UserRepository userRepository; + + public UserDto.Response save(UserDto.Request request) { + User user = UserDto.toEntity(request); + return UserDto.toResponse(userRepository.save(user)); + } + + @Transactional(readOnly = true) + public List findAll() { + List users = userRepository.findAll(); + return users.stream().map(UserDto::toResponse).toList(); + } + + @Transactional(readOnly = true) + public UserDto.Response findById(Long id) { + User user = userRepository.findById(id).orElseThrow(NoSuchElementException::new); + return UserDto.toResponse(user); + } + + public void update(Long postId, UserDto.Request request) { + User user = userRepository.findById(postId).orElseThrow(NoSuchElementException::new); + user.changeUserInfo(request.name(), request.age(), request.hobby()); + } +} diff --git a/board/src/main/resources/application.yaml b/board/src/main/resources/application.yaml new file mode 100644 index 000000000..cb1a53d49 --- /dev/null +++ b/board/src/main/resources/application.yaml @@ -0,0 +1,9 @@ +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/board?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Seoul&characterEncoding=UTF-8 + username: root + password: + jpa: + hibernate: + ddl-auto: update \ No newline at end of file diff --git a/board/src/main/resources/static/docs/index.html b/board/src/main/resources/static/docs/index.html new file mode 100644 index 000000000..6b26dfe2d --- /dev/null +++ b/board/src/main/resources/static/docs/index.html @@ -0,0 +1,897 @@ + + + + + + + +게시글 + + + + + +
+
+

게시글

+
+
+

게시글 등록

+ +
+
+

/api/v1/posts

+
+
Request
+
+
POST /api/posts HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Content-Length: 48
+Host: localhost:8080
+
+{"userId":1,"title":"title","content":"content"}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

userId

Number

작성자 ID

title

String

게시글 제목

content

String

게시글 내용

+
+
Response
+
+
HTTP/1.1 201 Created
+Content-Type: application/json
+Content-Length: 161
+
+{"resultCode":"S01","msg":"성공","data":{"userId":1,"title":"title","content":"content","createdAt":"2023-11-20T23:49:20.0561503"},"fail":false,"success":true}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

resultCode

String

결과코드

success

Boolean

성공여부

fail

Boolean

실패여부

msg

String

결과메시지

data

Object

응답데이터

data.userId

Number

작성자 ID

data.title

String

게시글 제목

data.content

String

게시글 내용

data.createdAt

String

게시글 생성 시간

+
+
+

게시글 조회

+ +
+
+

/api/v1/posts

+
+
Request
+
+
GET /api/posts HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Host: localhost:8080
+
+
+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 477
+
+{"resultCode":"S01","msg":"성공","data":{"content":[{"userId":1,"title":"title","content":"content","createdAt":"2023-11-20T23:49:20.7001539"}],"pageable":{"pageNumber":0,"pageSize":10,"sort":{"empty":true,"sorted":false,"unsorted":true},"offset":0,"unpaged":false,"paged":true},"last":true,"totalPages":1,"totalElements":1,"size":10,"number":0,"sort":{"empty":true,"sorted":false,"unsorted":true},"first":true,"numberOfElements":1,"empty":false},"fail":false,"success":true}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

resultCode

String

결과코드

success

Boolean

성공여부

fail

Boolean

실패여부

msg

String

결과메시지

data.content[].userId

Number

작성자 ID

data.content[].title

String

게시글 제목

data.content[].content

String

게시글 내용

data.content[].createdAt

String

게시글 생성 시간

data.pageable.pageNumber

Number

페이지 번호

data.pageable.pageSize

Number

페이지 개수

data.pageable.sort.empty

Boolean

공백 여부

data.pageable.sort.sorted

Boolean

정렬 O

data.pageable.sort.unsorted

Boolean

정렬 X

data.pageable.offset

Number

오프셋

data.pageable.paged

Boolean

페이지 O

data.pageable.unpaged

Boolean

페이지 X

data.last

Boolean

마지막 여부

data.totalPages

Number

전체 페이지

data.totalElements

Number

전체 데이터 개수

data.first

Boolean

처음 여부

data.size

Number

크기

data.number

Number

번호

data.sort.empty

Boolean

정렬 공백 여부

data.sort.sorted

Boolean

정렬 여부(O)

data.sort.unsorted

Boolean

정렬 여부(X)

data.numberOfElements

Number

데이터 개수

data.empty

Boolean

공백 여부

+
+
+

게시글 ID로 조회

+ +
+
+

/api/v1/posts/{id}

+
+
Request
+
+
GET /api/posts/1 HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Host: localhost:8080
+
+
+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 161
+
+{"resultCode":"S01","msg":"성공","data":{"userId":1,"title":"title","content":"content","createdAt":"2023-11-20T23:49:20.8321529"},"fail":false,"success":true}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

resultCode

String

결과코드

success

Boolean

성공여부

fail

Boolean

실패여부

msg

String

결과메시지

data

Object

응답데이터

data.userId

Number

작성자 ID

data.title

String

게시글 제목

data.content

String

게시글 내용

data.createdAt

String

게시글 생성 시간

+
+
+

게시글 수정

+ +
+
+

/api/v1/posts/{id}

+
+
Request
+
+
POST /api/posts/1 HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Content-Length: 48
+Host: localhost:8080
+
+{"userId":1,"title":"title","content":"content"}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

userId

Number

작성자 ID

title

String

게시글 제목

content

String

게시글 내용

+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 75
+
+{"resultCode":"S01","msg":"성공","data":null,"fail":false,"success":true}
+
+
+
+
+
+
+ + + \ No newline at end of file diff --git a/board/src/test/java/com/example/board/BoardApplicationTests.java b/board/src/test/java/com/example/board/BoardApplicationTests.java new file mode 100644 index 000000000..a14884bae --- /dev/null +++ b/board/src/test/java/com/example/board/BoardApplicationTests.java @@ -0,0 +1,5 @@ +package com.example.board; + +class BoardApplicationTests { + +} diff --git a/board/src/test/java/com/example/board/controller/PostRestControllerTest.java b/board/src/test/java/com/example/board/controller/PostRestControllerTest.java new file mode 100644 index 000000000..26a799b51 --- /dev/null +++ b/board/src/test/java/com/example/board/controller/PostRestControllerTest.java @@ -0,0 +1,201 @@ +package com.example.board.controller; + +import com.example.board.service.PostService; +import com.fasterxml.jackson.databind.ObjectMapper; +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.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.mapping.JpaMetamodelMappingContext; +import org.springframework.http.MediaType; +import org.springframework.restdocs.payload.JsonFieldType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +import static com.example.board.dto.PostDto.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.payload.PayloadDocumentation.*; + +@AutoConfigureRestDocs +@AutoConfigureMockMvc +@MockBean(JpaMetamodelMappingContext.class) +@WebMvcTest({PostRestController.class}) +class PostRestControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private PostService service; + + @Autowired + private ObjectMapper objectMapper; + + @Test + void saveTest() throws Exception { + Request request = Request.builder() + .userId(1L) + .title("title") + .content("content") + .build(); + + Response response = Response.builder() + .userId(1L) + .title("title") + .content("content") + .createdAt(LocalDateTime.now()) + .build(); + + given(service.save(request)).willReturn(response); + String requestJson = objectMapper.writeValueAsString(request); + + mockMvc.perform(MockMvcRequestBuilders.post("/api/posts") + .content(requestJson) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isCreated()) + .andDo(document("post-save", + requestFields( + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("작성자 ID"), + fieldWithPath("title").type(JsonFieldType.STRING).description("게시글 제목"), + fieldWithPath("content").type(JsonFieldType.STRING).description("게시글 내용") + ), + responseFields( + fieldWithPath("resultCode").type(JsonFieldType.STRING).description("결과코드"), + fieldWithPath("success").type(JsonFieldType.BOOLEAN).description("성공여부"), + fieldWithPath("fail").type(JsonFieldType.BOOLEAN).description("실패여부"), + fieldWithPath("msg").type(JsonFieldType.STRING).description("결과메시지"), + fieldWithPath("data").description("응답데이터"), + fieldWithPath("data.userId").type(JsonFieldType.NUMBER).description("작성자 ID"), + fieldWithPath("data.title").type(JsonFieldType.STRING).description("게시글 제목"), + fieldWithPath("data.content").type(JsonFieldType.STRING).description("게시글 내용"), + fieldWithPath("data.createdAt").type(JsonFieldType.STRING).description("게시글 생성 시간") + ) + )); + } + + @Test + void findAllTest() throws Exception { + Request request = Request.builder() + .userId(1L) + .title("title") + .content("content") + .build(); + service.save(request); + + Response response = Response.builder() + .userId(1L) + .title("title") + .content("content") + .createdAt(LocalDateTime.now()) + .build(); + List responses = new ArrayList<>(); + responses.add(response); + + Pageable pageable = PageRequest.of(0, 10); + PageImpl pageResponse = new PageImpl<>(responses, pageable, responses.size()); + + given(service.findAll(PageRequest.of(0, 10))).willReturn(pageResponse); + mockMvc.perform(MockMvcRequestBuilders.get("/api/posts") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo(document("post-findAll", + responseFields( + fieldWithPath("resultCode").type(JsonFieldType.STRING).description("결과코드"), + fieldWithPath("success").type(JsonFieldType.BOOLEAN).description("성공여부"), + fieldWithPath("fail").type(JsonFieldType.BOOLEAN).description("실패여부"), + fieldWithPath("msg").type(JsonFieldType.STRING).description("결과메시지"), + fieldWithPath("data.content[].userId").description("작성자 ID"), + fieldWithPath("data.content[].title").type(JsonFieldType.STRING).description("게시글 제목"), + fieldWithPath("data.content[].content").type(JsonFieldType.STRING).description("게시글 내용"), + fieldWithPath("data.content[].createdAt").type(JsonFieldType.STRING).description("게시글 생성 시간"), + fieldWithPath("data.pageable.pageNumber").type(JsonFieldType.NUMBER).description("페이지 번호"), + fieldWithPath("data.pageable.pageSize").type(JsonFieldType.NUMBER).description("페이지 개수"), + fieldWithPath("data.pageable.sort.empty").type(JsonFieldType.BOOLEAN).description("공백 여부"), + fieldWithPath("data.pageable.sort.sorted").type(JsonFieldType.BOOLEAN).description("정렬 O"), + fieldWithPath("data.pageable.sort.unsorted").type(JsonFieldType.BOOLEAN).description("정렬 X"), + fieldWithPath("data.pageable.offset").type(JsonFieldType.NUMBER).description("오프셋"), + fieldWithPath("data.pageable.paged").type(JsonFieldType.BOOLEAN).description("페이지 O"), + fieldWithPath("data.pageable.unpaged").type(JsonFieldType.BOOLEAN).description("페이지 X"), + fieldWithPath("data.last").type(JsonFieldType.BOOLEAN).description("마지막 여부"), + fieldWithPath("data.totalPages").type(JsonFieldType.NUMBER).description("전체 페이지"), + fieldWithPath("data.totalElements").type(JsonFieldType.NUMBER).description("전체 데이터 개수"), + fieldWithPath("data.first").type(JsonFieldType.BOOLEAN).description("처음 여부"), + fieldWithPath("data.size").type(JsonFieldType.NUMBER).description("크기"), + fieldWithPath("data.number").type(JsonFieldType.NUMBER).description("번호"), + fieldWithPath("data.sort.empty").type(JsonFieldType.BOOLEAN).description("정렬 공백 여부"), + fieldWithPath("data.sort.sorted").type(JsonFieldType.BOOLEAN).description("정렬 여부(O)"), + fieldWithPath("data.sort.unsorted").type(JsonFieldType.BOOLEAN).description("정렬 여부(X)"), + fieldWithPath("data.numberOfElements").type(JsonFieldType.NUMBER).description("데이터 개수"), + fieldWithPath("data.empty").type(JsonFieldType.BOOLEAN).description("공백 여부") + ) + )); + } + + @Test + void findByIdTest() throws Exception { + Response response = Response.builder() + .userId(1L) + .title("title") + .content("content") + .createdAt(LocalDateTime.now()) + .build(); + + given(service.findById(1L)).willReturn(response); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/posts/{id}",1L) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo(document("post-findById", + responseFields( + fieldWithPath("resultCode").type(JsonFieldType.STRING).description("결과코드"), + fieldWithPath("success").type(JsonFieldType.BOOLEAN).description("성공여부"), + fieldWithPath("fail").type(JsonFieldType.BOOLEAN).description("실패여부"), + fieldWithPath("msg").type(JsonFieldType.STRING).description("결과메시지"), + fieldWithPath("data").description("응답데이터"), + fieldWithPath("data.userId").type(JsonFieldType.NUMBER).description("작성자 ID"), + fieldWithPath("data.title").type(JsonFieldType.STRING).description("게시글 제목"), + fieldWithPath("data.content").type(JsonFieldType.STRING).description("게시글 내용"), + fieldWithPath("data.createdAt").type(JsonFieldType.STRING).description("게시글 생성 시간") + ) + )); + } + + @Test + void updateTest() throws Exception { + Request request = Request.builder() + .userId(1L) + .title("title") + .content("content") + .build(); + service.save(request); + + String requestJson = objectMapper.writeValueAsString(request); + + mockMvc.perform(MockMvcRequestBuilders.post("/api/posts/{id}", 1L) + .content(requestJson) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andDo(document("post-update", + requestFields( + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("작성자 ID"), + fieldWithPath("title").type(JsonFieldType.STRING).description("게시글 제목"), + fieldWithPath("content").type(JsonFieldType.STRING).description("게시글 내용") + ) + )); + } +} \ No newline at end of file