diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..c2065bc26 --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..6d7ace3d5 --- /dev/null +++ b/build.gradle @@ -0,0 +1,55 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.2' + id 'io.spring.dependency-management' version '1.1.2' + id 'org.asciidoctor.jvm.convert' version '3.3.2' +} + +group = 'com.seungwon' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + asciidoctorExtensions +} + +repositories { + mavenCentral() +} + +ext { + set('snippetsDir', file("build/generated-snippets")) +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.h2database:h2' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' + asciidoctorExtensions 'org.springframework.restdocs:spring-restdocs-asciidoctor' +} + +tasks.named('test') { + outputs.dir snippetsDir + useJUnitPlatform() +} + +tasks.named('asciidoctor') { + inputs.dir snippetsDir + dependsOn test +} + + +bootJar { + dependsOn asciidoctor + copy { + from "${asciidoctor.outputDir}" + into 'BOOT-INF/classes/static/docs' + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..033e24c4c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..9f4197d5f --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 000000000..fcb6fca14 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..60debaaef --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'Board' diff --git a/src/main/java/com/seungwon/board/BoardApplication.java b/src/main/java/com/seungwon/board/BoardApplication.java new file mode 100644 index 000000000..553cbd436 --- /dev/null +++ b/src/main/java/com/seungwon/board/BoardApplication.java @@ -0,0 +1,13 @@ +package com.seungwon.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/src/main/java/com/seungwon/board/common/BaseEntity.java b/src/main/java/com/seungwon/board/common/BaseEntity.java new file mode 100644 index 000000000..fe073b1fe --- /dev/null +++ b/src/main/java/com/seungwon/board/common/BaseEntity.java @@ -0,0 +1,29 @@ +package com.seungwon.board.common; + +import java.time.LocalDateTime; + +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; + +@Getter +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public abstract class BaseEntity { + @CreatedDate + @Column(updatable = false) + protected LocalDateTime createdAt; + + @CreatedBy + @Column(updatable = false) + protected String createdBy; + + @LastModifiedDate + protected LocalDateTime updatedAt; +} diff --git a/src/main/java/com/seungwon/board/common/ErrorResponse.java b/src/main/java/com/seungwon/board/common/ErrorResponse.java new file mode 100644 index 000000000..1b3ef6531 --- /dev/null +++ b/src/main/java/com/seungwon/board/common/ErrorResponse.java @@ -0,0 +1,24 @@ +package com.seungwon.board.common; + +import java.time.LocalDateTime; + +import org.springframework.http.HttpStatus; + +import lombok.Builder; + +public record ErrorResponse( + LocalDateTime timestamp, + HttpStatus status, + int code, + String message +) { + @Builder + public ErrorResponse(HttpStatus status, String message) { + this( + LocalDateTime.now(), + status, + status.value(), + message + ); + } +} diff --git a/src/main/java/com/seungwon/board/common/GlobalExceptionHandler.java b/src/main/java/com/seungwon/board/common/GlobalExceptionHandler.java new file mode 100644 index 000000000..26dae4b63 --- /dev/null +++ b/src/main/java/com/seungwon/board/common/GlobalExceptionHandler.java @@ -0,0 +1,52 @@ +package com.seungwon.board.common; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import com.seungwon.board.common.exception.InvalidDataException; +import com.seungwon.board.common.exception.InvalidRequestException; +import com.seungwon.board.common.exception.NoSuchDataException; + +@RestControllerAdvice +public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { + @ExceptionHandler(NoSuchDataException.class) + public ResponseEntity noSuchDataException(NoSuchDataException ex, + WebRequest request) { + + ErrorResponse errorResponse = ErrorResponse.builder() + .status(HttpStatus.NOT_FOUND) + .message(ex.getMessage()) + .build(); + + return handleExceptionInternal(ex, errorResponse, null, HttpStatus.NOT_FOUND, request); + } + + @ExceptionHandler(InvalidRequestException.class) + public ResponseEntity invalidRequestException(InvalidRequestException ex, + WebRequest request) { + + ErrorResponse errorResponse = ErrorResponse.builder() + .status(HttpStatus.BAD_REQUEST) + .message(ex.getMessage()) + .build(); + + return handleExceptionInternal(ex, errorResponse, null, HttpStatus.BAD_REQUEST, request); + } + + @ExceptionHandler(InvalidDataException.class) + public ResponseEntity invalidDataException(InvalidDataException ex, + WebRequest request) { + + ErrorResponse errorResponse = ErrorResponse.builder() + .status(HttpStatus.METHOD_NOT_ALLOWED) + .message(ex.getMessage()) + .build(); + + return handleExceptionInternal(ex, errorResponse, null, HttpStatus.METHOD_NOT_ALLOWED, request); + } + +} diff --git a/src/main/java/com/seungwon/board/common/exception/InvalidDataException.java b/src/main/java/com/seungwon/board/common/exception/InvalidDataException.java new file mode 100644 index 000000000..7d467dd5a --- /dev/null +++ b/src/main/java/com/seungwon/board/common/exception/InvalidDataException.java @@ -0,0 +1,10 @@ +package com.seungwon.board.common.exception; + +public class InvalidDataException extends RuntimeException { + public InvalidDataException() { + } + + public InvalidDataException(String message) { + super(message); + } +} diff --git a/src/main/java/com/seungwon/board/common/exception/InvalidRequestException.java b/src/main/java/com/seungwon/board/common/exception/InvalidRequestException.java new file mode 100644 index 000000000..0a6e58444 --- /dev/null +++ b/src/main/java/com/seungwon/board/common/exception/InvalidRequestException.java @@ -0,0 +1,10 @@ +package com.seungwon.board.common.exception; + +public class InvalidRequestException extends RuntimeException { + public InvalidRequestException() { + } + + public InvalidRequestException(String message) { + super(message); + } +} diff --git a/src/main/java/com/seungwon/board/common/exception/NoSuchDataException.java b/src/main/java/com/seungwon/board/common/exception/NoSuchDataException.java new file mode 100644 index 000000000..57bbb2b7e --- /dev/null +++ b/src/main/java/com/seungwon/board/common/exception/NoSuchDataException.java @@ -0,0 +1,10 @@ +package com.seungwon.board.common.exception; + +public class NoSuchDataException extends RuntimeException { + public NoSuchDataException() { + } + + public NoSuchDataException(String message) { + super(message); + } +} diff --git a/src/main/java/com/seungwon/board/member/application/MemberService.java b/src/main/java/com/seungwon/board/member/application/MemberService.java new file mode 100644 index 000000000..e9a75c6a4 --- /dev/null +++ b/src/main/java/com/seungwon/board/member/application/MemberService.java @@ -0,0 +1,31 @@ +package com.seungwon.board.member.application; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.seungwon.board.member.application.dto.MemberRequestDto; +import com.seungwon.board.member.domain.Member; +import com.seungwon.board.member.infra.MemberRepository; + +@Service +@Transactional +public class MemberService { + private final MemberRepository memberRepository; + + public MemberService(MemberRepository memberRepository) { + this.memberRepository = memberRepository; + } + + public Long create(MemberRequestDto memberRequestDto) { + Member member = Member.builder() + .age(memberRequestDto.age()) + .hobby(memberRequestDto.hobby()) + .name(memberRequestDto.name()) + .build(); + + Member result = memberRepository.save(member); + + return result.getId(); + } + +} diff --git a/src/main/java/com/seungwon/board/member/application/dto/MemberRequestDto.java b/src/main/java/com/seungwon/board/member/application/dto/MemberRequestDto.java new file mode 100644 index 000000000..a4bfae1ea --- /dev/null +++ b/src/main/java/com/seungwon/board/member/application/dto/MemberRequestDto.java @@ -0,0 +1,8 @@ +package com.seungwon.board.member.application.dto; + +public record MemberRequestDto( + String name, + int age, + String hobby +) { +} diff --git a/src/main/java/com/seungwon/board/member/domain/Member.java b/src/main/java/com/seungwon/board/member/domain/Member.java new file mode 100644 index 000000000..f454d55cf --- /dev/null +++ b/src/main/java/com/seungwon/board/member/domain/Member.java @@ -0,0 +1,74 @@ +package com.seungwon.board.member.domain; + +import java.text.MessageFormat; + +import com.seungwon.board.common.BaseEntity; +import com.seungwon.board.common.exception.InvalidDataException; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Member extends BaseEntity { + private static final int NAME_MAX_LENGTH = 10; + private static final int HOBBY_MAX_LENGTH = 100; + private static final int MAX_AGE = 120; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + Long id; + + @Column(nullable = false, length = 10) + String name; + + int age; + + @Column(nullable = false, length = 100) + String hobby; + + @Builder + public Member(String name, int age, String hobby) { + validateName(name); + validateAge(age); + validateHobby(hobby); + this.name = name; + this.age = age; + this.hobby = hobby; + } + + private void validateName(String name) { + boolean onlyContainsCharacters = name.chars().allMatch(Character::isLetter); + if (!onlyContainsCharacters) { + throw new InvalidDataException( + MessageFormat.format("입력된 이름={0}. 이름에는 문자만 입력 가능합니다.", name)); + } + if (name.length() > 10 || name.isBlank()) { + throw new InvalidDataException( + MessageFormat.format("입력된 이름={0}자. 이름은 최대 {1}자 입력 가능합니다.", name.length(), NAME_MAX_LENGTH)); + } + } + + private void validateAge(int age) { + if (!(0 < age && age <= MAX_AGE)) { + throw new InvalidDataException( + MessageFormat.format("입력된 나이={0}. 나이는 0 이상 {1} 이하의 숫자로 입력해주세요.", age, MAX_AGE)); + } + } + + private void validateHobby(String hobby) { + if (hobby.length() > 100 || hobby.isBlank()) { + throw new InvalidDataException( + MessageFormat.format("입력된 취미={0}자. 취미는 최대 {1}자 입력 가능합니다.", hobby.length(), HOBBY_MAX_LENGTH)); + } + } + +} diff --git a/src/main/java/com/seungwon/board/member/infra/MemberRepository.java b/src/main/java/com/seungwon/board/member/infra/MemberRepository.java new file mode 100644 index 000000000..2d26c2f12 --- /dev/null +++ b/src/main/java/com/seungwon/board/member/infra/MemberRepository.java @@ -0,0 +1,10 @@ +package com.seungwon.board.member.infra; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.seungwon.board.member.domain.Member; + +@Repository +public interface MemberRepository extends JpaRepository { +} diff --git a/src/main/java/com/seungwon/board/member/presentation/MemberController.java b/src/main/java/com/seungwon/board/member/presentation/MemberController.java new file mode 100644 index 000000000..6d170cb32 --- /dev/null +++ b/src/main/java/com/seungwon/board/member/presentation/MemberController.java @@ -0,0 +1,27 @@ +package com.seungwon.board.member.presentation; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.seungwon.board.member.application.MemberService; +import com.seungwon.board.member.application.dto.MemberRequestDto; + +@RestController +@RequestMapping("/api/v1/members") +public class MemberController { + private final MemberService memberService; + + public MemberController(MemberService memberService) { + this.memberService = memberService; + } + + @PostMapping() + ResponseEntity create(@RequestBody MemberRequestDto memberRequestDto) { + Long id = memberService.create(memberRequestDto); + return ResponseEntity.ok(id); + } + +} diff --git a/src/main/java/com/seungwon/board/post/application/PostService.java b/src/main/java/com/seungwon/board/post/application/PostService.java new file mode 100644 index 000000000..ffeef4dc4 --- /dev/null +++ b/src/main/java/com/seungwon/board/post/application/PostService.java @@ -0,0 +1,65 @@ +package com.seungwon.board.post.application; + +import java.text.MessageFormat; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.seungwon.board.common.exception.InvalidRequestException; +import com.seungwon.board.common.exception.NoSuchDataException; +import com.seungwon.board.member.domain.Member; +import com.seungwon.board.member.infra.MemberRepository; +import com.seungwon.board.post.application.dto.PostRequestDto; +import com.seungwon.board.post.application.dto.PostResponseDto; +import com.seungwon.board.post.application.dto.PostSaveRequestDto; +import com.seungwon.board.post.domain.Post; +import com.seungwon.board.post.infra.PostRepository; + +@Service +@Transactional +public class PostService { + private final PostRepository postRepository; + private final MemberRepository memberRepository; + + public PostService(PostRepository postRepository, MemberRepository memberRepository) { + this.postRepository = postRepository; + this.memberRepository = memberRepository; + } + + public Page findAll(Pageable pageable) { + return postRepository.findAll(pageable) + .map(PostResponseDto::new); + } + + public PostResponseDto findBy(Long id) { + Post post = postRepository.findById(id) + .orElseThrow(() -> new NoSuchDataException(MessageFormat.format("해당 포스트가 존재하지 않습니다[id={0}] ", id))); + + return new PostResponseDto(post); + } + + public PostSaveRequestDto create(PostRequestDto postRequestDto) { + Long userId = postRequestDto.writerId(); + Member member = memberRepository.findById(userId).orElseThrow(); + + Post post = Post.builder() + .writer(member) + .title(postRequestDto.title()) + .content(postRequestDto.content()) + .build(); + Post result = postRepository.save(post); + + return new PostSaveRequestDto(result); + } + + public PostSaveRequestDto update(Long id, PostRequestDto postRequestDto) { + Post post = postRepository.findById(id) + .orElseThrow(() -> new InvalidRequestException( + MessageFormat.format("존재하지 않는 포스트에 대한 수정 요청입니다[id={0}] ", id))); + + post.modify(postRequestDto.title(), postRequestDto.content(), postRequestDto.writerId()); + return new PostSaveRequestDto(post); + } +} diff --git a/src/main/java/com/seungwon/board/post/application/dto/PostRequestDto.java b/src/main/java/com/seungwon/board/post/application/dto/PostRequestDto.java new file mode 100644 index 000000000..4cbf339de --- /dev/null +++ b/src/main/java/com/seungwon/board/post/application/dto/PostRequestDto.java @@ -0,0 +1,12 @@ +package com.seungwon.board.post.application.dto; + +import lombok.Builder; + +@Builder +public record PostRequestDto( + String content, + String title, + Long writerId + +) { +} diff --git a/src/main/java/com/seungwon/board/post/application/dto/PostResponseDto.java b/src/main/java/com/seungwon/board/post/application/dto/PostResponseDto.java new file mode 100644 index 000000000..fcbab0949 --- /dev/null +++ b/src/main/java/com/seungwon/board/post/application/dto/PostResponseDto.java @@ -0,0 +1,23 @@ +package com.seungwon.board.post.application.dto; + +import java.time.LocalDateTime; + +import com.seungwon.board.post.domain.Post; + +public record PostResponseDto( + Long id, + String content, + String title, + Long writerId, + LocalDateTime updatedAt + +) { + public PostResponseDto(Post post) { + this(post.getId(), + post.getContent(), + post.getTitle(), + post.getWriter().getId(), + post.getUpdatedAt() + ); + } +} diff --git a/src/main/java/com/seungwon/board/post/application/dto/PostSaveRequestDto.java b/src/main/java/com/seungwon/board/post/application/dto/PostSaveRequestDto.java new file mode 100644 index 000000000..03284b9b7 --- /dev/null +++ b/src/main/java/com/seungwon/board/post/application/dto/PostSaveRequestDto.java @@ -0,0 +1,14 @@ +package com.seungwon.board.post.application.dto; + +import java.time.LocalDateTime; + +import com.seungwon.board.post.domain.Post; + +public record PostSaveRequestDto( + Long id, + LocalDateTime updatedAt +) { + public PostSaveRequestDto(Post post) { + this(post.getId(), post.getUpdatedAt()); + } +} diff --git a/src/main/java/com/seungwon/board/post/domain/Post.java b/src/main/java/com/seungwon/board/post/domain/Post.java new file mode 100644 index 000000000..a915c7d9c --- /dev/null +++ b/src/main/java/com/seungwon/board/post/domain/Post.java @@ -0,0 +1,74 @@ +package com.seungwon.board.post.domain; + +import java.text.MessageFormat; + +import com.seungwon.board.common.BaseEntity; +import com.seungwon.board.common.exception.InvalidDataException; +import com.seungwon.board.common.exception.InvalidRequestException; +import com.seungwon.board.member.domain.Member; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.Lob; +import jakarta.persistence.ManyToOne; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Post extends BaseEntity { + private static final int TITLE_MAX_LENGTH = 100; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + Long id; + + @Column(nullable = false, length = TITLE_MAX_LENGTH) + String title; + + @Column(nullable = false) + @Lob + String content; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(referencedColumnName = "id") + Member writer; + + @Builder + public Post(String title, String content, Member writer) { + validateTitle(title); + this.title = title; + this.content = content; + this.writer = writer; + createdBy = writer.getName(); + } + + private void validateTitle(String title) { + if (title.length() > TITLE_MAX_LENGTH || title.isBlank()) { + throw new InvalidDataException( + MessageFormat.format("입력된 제목={0}자. 제목은 최대 {1}자 입력 가능합니다.", title.length(), TITLE_MAX_LENGTH)); + } + } + + public void modify(@NonNull String title, String content, Long updater) { + Long initialWriter = this.writer.getId(); + + if (updater != initialWriter) { + throw new InvalidRequestException( + MessageFormat.format("작성자가 아닌 경우 글 수정이 불가능합니다[기존 작성자 id={0}, 요청된 작성자 id={1}] ", initialWriter, updater) + ); + } + + this.title = title; + this.content = content; + } +} diff --git a/src/main/java/com/seungwon/board/post/infra/PostRepository.java b/src/main/java/com/seungwon/board/post/infra/PostRepository.java new file mode 100644 index 000000000..e7fc3ec5f --- /dev/null +++ b/src/main/java/com/seungwon/board/post/infra/PostRepository.java @@ -0,0 +1,10 @@ +package com.seungwon.board.post.infra; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.seungwon.board.post.domain.Post; + +@Repository +public interface PostRepository extends JpaRepository { +} diff --git a/src/main/java/com/seungwon/board/post/presentation/PostController.java b/src/main/java/com/seungwon/board/post/presentation/PostController.java new file mode 100644 index 000000000..0322a3ead --- /dev/null +++ b/src/main/java/com/seungwon/board/post/presentation/PostController.java @@ -0,0 +1,63 @@ +package com.seungwon.board.post.presentation; + +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.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.seungwon.board.post.application.PostService; +import com.seungwon.board.post.application.dto.PostRequestDto; +import com.seungwon.board.post.application.dto.PostResponseDto; +import com.seungwon.board.post.application.dto.PostSaveRequestDto; + +@RestController +@RequestMapping("/api/v1/posts") +public class PostController { + private final PostService postService; + + public PostController(PostService postService) { + this.postService = postService; + } + + @GetMapping() + ResponseEntity> findAll( + @PageableDefault(sort = "id", size = 5, direction = Sort.Direction.ASC) + Pageable pageable) { + + Page response = postService.findAll(pageable); + + return ResponseEntity.ok(response); + } + + @GetMapping("/{id}") + ResponseEntity findBy(@PathVariable("id") Long id) { + + PostResponseDto response = postService.findBy(id); + + return ResponseEntity.ok(response); + } + + @PostMapping() + ResponseEntity create(@RequestBody PostRequestDto postRequestDto) { + + PostSaveRequestDto postSaveRequestDto = postService.create(postRequestDto); + + return ResponseEntity.ok(postSaveRequestDto); + } + + @PatchMapping("/{id}") + ResponseEntity update(@PathVariable("id") Long id, @RequestBody PostRequestDto postRequestDto) { + + PostSaveRequestDto postSaveRequestDto = postService.update(id, postRequestDto); + + return ResponseEntity.ok(postSaveRequestDto); + } +} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 000000000..0c88ba511 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,15 @@ +spring: + h2: + console: + enabled: true + jpa: + generate-ddl: true + database: h2 + show-sql: true + open-in-view: false + properties: + hibernate: + dialect: org.hibernate.dialect.H2Dialect + query.in_clause_parameter_padding: true + hbm2ddl: + auto: create diff --git a/src/main/resources/static/api-docs.html b/src/main/resources/static/api-docs.html new file mode 100644 index 000000000..c42fd5261 --- /dev/null +++ b/src/main/resources/static/api-docs.html @@ -0,0 +1,918 @@ + + + + + + + +API Document + + + + + + +
+
+

게시글 관련 API

+
+
+

1. 게시글 생성

+
+
Request
+
+
POST /posts HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Content-Length: 86
+Host: localhost:8080
+
+{
+  "content" : "게시글 내용",
+  "title" : "게시글 제목",
+  "writerId" : 1
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

content

String

게시글 내용

title

String

게시글 제목

writerId

Number

작성자 아이디

+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 60
+
+{
+  "id" : 2,
+  "updatedAt" : "2023-08-05T02:24:37.994097"
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

id

Number

생성된 게시글의 아이디

updatedAt

String

게시글 생성 날짜 및 시간

+
+
+

2. 게시글 조회

+
+

전체 조회(페이징 조회)

+
+
Request
+
+
GET /posts?page=0&size=5 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: 631
+
+{
+  "content" : [ {
+    "id" : 3,
+    "content" : "게시글 내용",
+    "title" : "게시글 제목",
+    "writerId" : 2,
+    "updatedAt" : "2023-08-05T02:24:38.089497"
+  } ],
+  "pageable" : {
+    "sort" : {
+      "empty" : false,
+      "sorted" : true,
+      "unsorted" : false
+    },
+    "offset" : 0,
+    "pageNumber" : 0,
+    "pageSize" : 5,
+    "paged" : true,
+    "unpaged" : false
+  },
+  "last" : true,
+  "totalPages" : 1,
+  "totalElements" : 1,
+  "first" : true,
+  "size" : 5,
+  "number" : 0,
+  "sort" : {
+    "empty" : false,
+    "sorted" : true,
+    "unsorted" : false
+  },
+  "numberOfElements" : 1,
+  "empty" : false
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

content[].id

Number

게시글 아이디

content[].title

String

게시글 제목

content[].content

String

게시글 내용

content[].writerId

Number

작성자 아이디

content[].updatedAt

String

가장 최근의 수정일

pageable.sort.sorted

Boolean

정렬 여부

pageable.sort.empty

Boolean

데이터가 비었는지 여부

pageable.sort.unsorted

Boolean

정렬 안 됐는지 여부

pageable.offset

Number

몇 번째 데이터인지 (0부터 시작)

pageable.pageNumber

Number

현재 페이지 번호

pageable.pageSize

Number

한 페이지당 조회할 데이터 개수

pageable.paged

Boolean

페이징 정보를 포함하는지 여부

pageable.unpaged

Boolean

페이징 정보를 포함하지 않는지 여부

last

Boolean

마지막 페이지인지 여부

totalPages

Number

전체 페이지 개수

totalElements

Number

테이블 총 데이터 개수

first

Boolean

첫번째 페이지인지 여부

numberOfElements

Number

요청 페이지에서 조회 된 데이터 개수

number

Number

현재 페이지 번호

size

Number

각 페이지별로 조회할 데이터 개수

sort.sorted

Boolean

정렬 됐는지 여부

sort.unsorted

Boolean

정렬 안 됐는지 여부

sort.empty

Boolean

데이터가 비었는지 여부

empty

Boolean

데이터가 비었는지 여부

+
+
+

단건 조회(아이디로 조회)

+
+
Request
+
+
GET /posts/5 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: 144
+
+{
+  "id" : 5,
+  "content" : "게시글 내용",
+  "title" : "게시글 제목",
+  "writerId" : 4,
+  "updatedAt" : "2023-08-05T02:24:38.152798"
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

id

Number

게시글 아이디

title

String

게시글 제목

content

String

게시글 내용

writerId

Number

작성자 아이디

updatedAt

String

가장 최근의 수정일

+
+
+
+

3. 게시글 수정

+
+
Request
+
+
PATCH /posts/4 HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Content-Length: 86
+Host: localhost:8080
+
+{
+  "content" : "게시글 내용",
+  "title" : "게시글 제목",
+  "writerId" : 3
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

content

String

게시글 내용

title

String

게시글 제목

writerId

Number

작성자 아이디

+
+
Response
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 60
+
+{
+  "id" : 4,
+  "updatedAt" : "2023-08-05T02:24:38.133667"
+}
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

id

Number

생성된 게시글의 아이디

updatedAt

String

수정된 날짜 및 시간

+
+
+
+
+ + + + + + \ No newline at end of file diff --git a/src/test/java/com/seungwon/board/BoardApplicationTests.java b/src/test/java/com/seungwon/board/BoardApplicationTests.java new file mode 100644 index 000000000..7d7f025ba --- /dev/null +++ b/src/test/java/com/seungwon/board/BoardApplicationTests.java @@ -0,0 +1,208 @@ +package com.seungwon.board; + +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; +import static org.springframework.restdocs.payload.PayloadDocumentation.*; +import static org.springframework.restdocs.request.RequestDocumentation.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import org.junit.jupiter.api.AfterEach; +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.http.MediaType; +import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; +import org.springframework.restdocs.payload.JsonFieldType; +import org.springframework.test.web.servlet.MockMvc; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.seungwon.board.member.domain.Member; +import com.seungwon.board.member.infra.MemberRepository; +import com.seungwon.board.post.application.dto.PostRequestDto; +import com.seungwon.board.post.domain.Post; +import com.seungwon.board.post.infra.PostRepository; + +@AutoConfigureRestDocs +@AutoConfigureMockMvc +@SpringBootTest +class BoardApplicationTests { + @Autowired + ObjectMapper objectMapper; + @Autowired + private MockMvc mockMvc; + @Autowired + private MemberRepository memberRepository; + + @Autowired + private PostRepository postRepository; + + private Member member; + private Post post; + + @BeforeEach + void setup() { + member = Member.builder() + .hobby("운동") + .age(26) + .name("한승원") + .build(); + memberRepository.save(member); + post = Post.builder() + .writer(member) + .content("게시글 내용") + .title("게시글 제목") + .build(); + postRepository.save(post); + } + + @AfterEach + void tearDown() { + postRepository.deleteAll(); + memberRepository.deleteAll(); + } + + @Test + @DisplayName("게시글을 등록한다") + void create() throws Exception { + // given + // when + long memberId = member.getId(); + PostRequestDto postRequestDto = PostRequestDto.builder() + .title(post.getTitle()) + .content(post.getContent()) + .writerId(memberId) + .build(); + + // then + mockMvc.perform(post("/api/v1/posts") + .content(objectMapper.writeValueAsString(postRequestDto)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("post-create", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + requestFields( + fieldWithPath("content").type(JsonFieldType.STRING).description("게시글 내용"), + fieldWithPath("title").type(JsonFieldType.STRING).description("게시글 제목"), + fieldWithPath("writerId").type(JsonFieldType.NUMBER).description("작성자 아이디") + ), responseFields( + fieldWithPath("id").type(JsonFieldType.NUMBER).description("생성된 게시글의 아이디"), + fieldWithPath("updatedAt").type(JsonFieldType.STRING).description("게시글 생성 날짜 및 시간") + ) + )); + } + + @Test + @DisplayName("게시글을 전체 조회 한다") + void findAll() throws Exception { + // given + // when + // then + mockMvc.perform(get("/api/v1/posts") + .param("page", String.valueOf(0)) + .param("size", String.valueOf(5)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("post-inquiry-all", + preprocessResponse(prettyPrint()), + responseFields( + fieldWithPath("content[].id").type(JsonFieldType.NUMBER).description("게시글 아이디"), + fieldWithPath("content[].title").type(JsonFieldType.STRING).description("게시글 제목"), + fieldWithPath("content[].content").type(JsonFieldType.STRING).description("게시글 내용"), + fieldWithPath("content[].writerId").type(JsonFieldType.NUMBER).description("작성자 아이디"), + fieldWithPath("content[].updatedAt").type(JsonFieldType.STRING) + .description("가장 최근의 수정일"), + + fieldWithPath("pageable.sort.sorted").description("정렬 여부"), + fieldWithPath("pageable.sort.empty").description("데이터가 비었는지 여부"), + fieldWithPath("pageable.sort.unsorted").description("정렬 안 됐는지 여부"), + + fieldWithPath("pageable.offset").description("몇 번째 데이터인지 (0부터 시작)"), + fieldWithPath("pageable.pageNumber").description("현재 페이지 번호"), + fieldWithPath("pageable.pageSize").description("한 페이지당 조회할 데이터 개수"), + fieldWithPath("pageable.paged").description("페이징 정보를 포함하는지 여부"), + fieldWithPath("pageable.unpaged").description("페이징 정보를 포함하지 않는지 여부"), + + fieldWithPath("last").description("마지막 페이지인지 여부"), + fieldWithPath("totalPages").description("전체 페이지 개수"), + fieldWithPath("totalElements").description("테이블 총 데이터 개수"), + fieldWithPath("first").description("첫번째 페이지인지 여부"), + fieldWithPath("numberOfElements").description("요청 페이지에서 조회 된 데이터 개수"), + fieldWithPath("number").description("현재 페이지 번호"), + fieldWithPath("size").description("각 페이지별로 조회할 데이터 개수"), + + fieldWithPath("sort.sorted").description("정렬 됐는지 여부"), + fieldWithPath("sort.unsorted").description("정렬 안 됐는지 여부"), + fieldWithPath("sort.empty").description("데이터가 비었는지 여부"), + + fieldWithPath("empty").description("데이터가 비었는지 여부") + + ) + )); + } + + @Test + @DisplayName("게시글을 id로 단건 조회 한다") + void findOneById() throws Exception { + // given + // when + Long id = post.getId(); + // then + mockMvc.perform(RestDocumentationRequestBuilders.get("/api/v1/posts/{id}", id) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("post-inquiry-id", + preprocessResponse(prettyPrint()), + pathParameters( + parameterWithName("id").description("조회하고자 하는 게시글의 ID") + ), + responseFields( + fieldWithPath("id").type(JsonFieldType.NUMBER).description("게시글 아이디"), + fieldWithPath("title").type(JsonFieldType.STRING).description("게시글 제목"), + fieldWithPath("content").type(JsonFieldType.STRING).description("게시글 내용"), + fieldWithPath("writerId").type(JsonFieldType.NUMBER).description("작성자 아이디"), + fieldWithPath("updatedAt").type(JsonFieldType.STRING).description("가장 최근의 수정일") + ) + )); + } + + @Test + @DisplayName("게시글을 수정한다") + void update() throws Exception { + // given + // when + long memberId = member.getId(); + PostRequestDto postRequestDto = PostRequestDto.builder() + .title(post.getTitle()) + .content(post.getContent()) + .writerId(memberId) + .build(); + long postId = post.getId(); + // then + mockMvc.perform(RestDocumentationRequestBuilders.patch("/api/v1/posts/{id}", postId) + .content(objectMapper.writeValueAsString(postRequestDto)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("post-update", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + pathParameters( + parameterWithName("id").description("수정하고자 하는 게시글의 ID") + ), + requestFields( + fieldWithPath("content").type(JsonFieldType.STRING).description("게시글 내용"), + fieldWithPath("title").type(JsonFieldType.STRING).description("게시글 제목"), + fieldWithPath("writerId").type(JsonFieldType.NUMBER).description("작성자 아이디") + ), responseFields( + fieldWithPath("id").type(JsonFieldType.NUMBER).description("생성된 게시글의 아이디"), + fieldWithPath("updatedAt").type(JsonFieldType.STRING).description("수정된 날짜 및 시간") + ) + )); + } + +} diff --git a/src/test/java/com/seungwon/board/member/MemberTest.java b/src/test/java/com/seungwon/board/member/MemberTest.java new file mode 100644 index 000000000..2729dd834 --- /dev/null +++ b/src/test/java/com/seungwon/board/member/MemberTest.java @@ -0,0 +1,79 @@ +package com.seungwon.board.member; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import com.seungwon.board.common.exception.InvalidDataException; +import com.seungwon.board.member.domain.Member; + +class MemberTest { + private static final int MAX_AGE = 120; + + @DisplayName("이름이 비어있거나 최대 길이 이상인 경우 예외가 발생한다") + @ParameterizedTest + @ValueSource(strings = { + "", + "가나다라마바사아자차카" + }) + void name_length_validation(String name) { + // given + String validHobby = "운동"; + int validAge = 26; + + // when + + // then + assertThrows(InvalidDataException.class, () -> new Member(name, validAge, validHobby)); + } + + @DisplayName("이름에 문자외에 숫자나 특수문자가 포함된다면 예외가 발생한다") + @ParameterizedTest + @ValueSource(strings = { + "1234", + "가#나$" + }) + void name_character_validation(String name) { + // given + String validHobby = "운동"; + int validAge = 26; + + // when + + // then + assertThrows(InvalidDataException.class, () -> new Member(name, validAge, validHobby)); + } + + @DisplayName("나이가 0 이하 또는 최대 연령 이상인 경우 예외가 발생한다") + @ParameterizedTest + @ValueSource(ints = {-1, 0, MAX_AGE + 1}) + void age_validation(int age) { + // given + String validHobby = "운동"; + String validName = "한승원"; + + // when + + // then + assertThrows(InvalidDataException.class, () -> new Member(validName, age, validHobby)); + } + + @DisplayName("입력된 취미가 비어있거나 최대 글자수 이상인 경우 예외가 발생한다") + @ParameterizedTest + @ValueSource(strings = { + "", + "사용자의 취미를 여기에 입력합니다. 취미에 최대 글자 개수 이상의 문자열이 입력되는 경우 테스트로 예외가 발생함을 검증하기 위해 입력하는 취미란에 입력될 수 있는 예시 문자열입니다." + }) + void hobby_validation(String hobby) { + // given + String validName = "한승원"; + int validAge = 26; + + // when + + // then + assertThrows(InvalidDataException.class, () -> new Member(validName, validAge, hobby)); + } +} diff --git a/src/test/java/com/seungwon/board/post/PostTest.java b/src/test/java/com/seungwon/board/post/PostTest.java new file mode 100644 index 000000000..b9e26dbd5 --- /dev/null +++ b/src/test/java/com/seungwon/board/post/PostTest.java @@ -0,0 +1,33 @@ +package com.seungwon.board.post; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mock; + +import com.seungwon.board.common.exception.InvalidDataException; +import com.seungwon.board.member.domain.Member; +import com.seungwon.board.post.domain.Post; + +class PostTest { + @Mock + private Member member; + + @ParameterizedTest + @ValueSource(strings = { + "", + "게시글의 제목을 여기에 입력합니다. 제목에 최대 글자 개수 이상의 문자열이 입력되는 경우 테스트로 예외가 발생함을 검증하기 위해 입력하는 제목에 입력될 수 있는 테스트 문자열입니다." + }) + @DisplayName("제목이 비어있거나 최대 입력 가능 길이보다 긴 경우 예외가 발생한다") + void title_validation(String title) { + // given + String validContent = "게시글내용"; + + // when + + // then + assertThrows(InvalidDataException.class, () -> new Post(title, validContent, member)); + } +}