diff --git a/week3/Advanced/ThirdAdvanced/.gitignore b/week3/Advanced/ThirdAdvanced/.gitignore new file mode 100644 index 0000000..77a10f9 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/.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/ + +### application.yml ### +resources \ No newline at end of file diff --git a/week3/Advanced/ThirdAdvanced/build.gradle b/week3/Advanced/ThirdAdvanced/build.gradle new file mode 100644 index 0000000..bd6310c --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/build.gradle @@ -0,0 +1,38 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '2.7.11' + id 'io.spring.dependency-management' version '1.0.15.RELEASE' +} + +group = 'sopt.org' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '11' + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-validation' + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + + // Health Check + implementation 'org.springframework.boot:spring-boot-starter-actuator' + + // JPA & Database + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'mysql:mysql-connector-java:8.0.32' +} + +tasks.named('test') { + useJUnitPlatform() +} \ No newline at end of file diff --git a/week3/Advanced/ThirdAdvanced/gradle/wrapper/gradle-wrapper.jar b/week3/Advanced/ThirdAdvanced/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/week3/Advanced/ThirdAdvanced/gradle/wrapper/gradle-wrapper.jar differ diff --git a/week3/Advanced/ThirdAdvanced/gradle/wrapper/gradle-wrapper.properties b/week3/Advanced/ThirdAdvanced/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..774fae8 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/week3/Advanced/ThirdAdvanced/gradlew b/week3/Advanced/ThirdAdvanced/gradlew new file mode 100755 index 0000000..a69d9cb --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/gradlew @@ -0,0 +1,240 @@ +#!/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/master/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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 + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# 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/week3/Advanced/ThirdAdvanced/gradlew.bat b/week3/Advanced/ThirdAdvanced/gradlew.bat new file mode 100644 index 0000000..53a6b23 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/gradlew.bat @@ -0,0 +1,91 @@ +@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=. +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/week3/Advanced/ThirdAdvanced/settings.gradle b/week3/Advanced/ThirdAdvanced/settings.gradle new file mode 100644 index 0000000..494d14a --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'ThirdAdvanced' diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/ThirdAdvancedApplication.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/ThirdAdvancedApplication.java new file mode 100644 index 0000000..228322e --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/ThirdAdvancedApplication.java @@ -0,0 +1,15 @@ +package sopt.org.ThirdAdvanced; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@SpringBootApplication +@EnableJpaAuditing +public class ThirdAdvancedApplication { + + public static void main(String[] args) { + SpringApplication.run(ThirdAdvancedApplication.class, args); + } + +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/common/advice/ControllerExceptionAdvice.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/common/advice/ControllerExceptionAdvice.java new file mode 100644 index 0000000..695cb71 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/common/advice/ControllerExceptionAdvice.java @@ -0,0 +1,57 @@ +package sopt.org.ThirdAdvanced.common.advice; + +import org.springframework.dao.DuplicateKeyException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +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 sopt.org.ThirdAdvanced.common.dto.ApiResponse; +import sopt.org.ThirdAdvanced.exception.CustomException; +import sopt.org.ThirdAdvanced.response.FailStatus; + +import java.util.Objects; + +@RestControllerAdvice +public class ControllerExceptionAdvice { + + /** + * 400 BAD_REQUEST + */ + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(MethodArgumentNotValidException.class) // @Valid 유효성 검사에서 발생하는 예외 + protected ApiResponse handleMethodArgumentNotValidException(final MethodArgumentNotValidException e) { + FieldError fieldError = Objects.requireNonNull(e.getFieldError()); + return ApiResponse.fail(FailStatus.VALIDATION_EXCEPTION, String.format("%s. (%s)", fieldError.getDefaultMessage(), fieldError.getField())); + } + + /** + * 404 NOT_FOUND + */ + @ResponseStatus(HttpStatus.NOT_FOUND) + @ExceptionHandler(CustomException.class) + protected ResponseEntity handleCustomException(final CustomException e) { + return ResponseEntity.status(e.getStatusCode()) + .body(ApiResponse.fail(e.getFailStatus(), e.getMessage())); + } + + /** + * 409 CONFLICT + */ + @ResponseStatus(HttpStatus.CONFLICT) + @ExceptionHandler(DuplicateKeyException.class) + protected ApiResponse handleDuplicationKeyException(final DuplicateKeyException e) { + return ApiResponse.fail(FailStatus.CONFLICT_NICKNAME_EXCEPTION); + } + + /** + * 500 SERVER_ERROR + */ +// @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) +// @ExceptionHandler(Exception.class) +// protected ApiResponse handleException(final Exception e) { +// return ApiResponse.fail(FailStatus.INTERNAL_SERVER_ERROR); +// } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/common/domain/BaseEntity.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/common/domain/BaseEntity.java new file mode 100644 index 0000000..9446d75 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/common/domain/BaseEntity.java @@ -0,0 +1,21 @@ +package sopt.org.ThirdAdvanced.common.domain; + +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.EntityListeners; +import javax.persistence.MappedSuperclass; +import java.time.LocalDateTime; + +@Getter +@MappedSuperclass //현재 이 엔티티 클래스를 다른 모든 엔티티들이 상속 받아야 하므로 어노테이션 붙여줌 +@EntityListeners(AuditingEntityListener.class) //JPA가 엔티티의 영속, 수정 이벤트를 감지해서 Auditing을 하도록 힘 +public abstract class BaseEntity { + @CreatedDate + private LocalDateTime createdAt; + + @LastModifiedDate + private LocalDateTime modifiedAt; +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/common/dto/ApiResponse.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/common/dto/ApiResponse.java new file mode 100644 index 0000000..0899247 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/common/dto/ApiResponse.java @@ -0,0 +1,39 @@ +package sopt.org.ThirdAdvanced.common.dto; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import sopt.org.ThirdAdvanced.response.FailStatus; +import sopt.org.ThirdAdvanced.response.SuccessStatus; + +@Getter //이거 안써주면 에러남. 왜그럴까 ? 이 고민은 PR 내용에 정리해둠. +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ApiResponse { + private final int status; + private final boolean success; + private final String message; + private T data; + + public static ApiResponse success(SuccessStatus success) { + return new ApiResponse(success.getStatusCode(), true, success.getMessage()); + } + + public static ApiResponse success(SuccessStatus success, T data) { + return new ApiResponse(success.getStatusCode(), true, success.getMessage(), data); + } + + public static ApiResponse fail(FailStatus fail) { + return new ApiResponse(fail.getStatusCode(), false, fail.getMessage()); + } + + // 더 자세한 에러 메세지를 내려주고 싶을 때, 메세지를 직접 작성해주기 위해 fail 메서드 오버로딩 + // 사용 예시) MethodArgumentNotValidException 예외 발생 시, 정확히 어떤 필드값이 문제인지 클라분들께 알려주기 위함. + public static ApiResponse fail(FailStatus fail, String message) { + return new ApiResponse(fail.getStatusCode(), false, message); + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/CommentController.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/CommentController.java new file mode 100644 index 0000000..c539ae3 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/CommentController.java @@ -0,0 +1,35 @@ +package sopt.org.ThirdAdvanced.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; +import sopt.org.ThirdAdvanced.common.dto.ApiResponse; +import sopt.org.ThirdAdvanced.controller.dto.request.CommentUploadDto; +import sopt.org.ThirdAdvanced.controller.dto.response.CommentListResponseDto; +import sopt.org.ThirdAdvanced.controller.dto.response.CommentResponseDto; +import sopt.org.ThirdAdvanced.response.SuccessStatus; +import sopt.org.ThirdAdvanced.service.CommentService; + +import javax.validation.Valid; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/comment") +public class CommentController { + + private final CommentService commentService; + + @PostMapping() + @ResponseStatus(HttpStatus.CREATED) + public ApiResponse uploadComment(@RequestBody @Valid final CommentUploadDto request){ + commentService.uploadComment(request); + return ApiResponse.success(SuccessStatus.CREATE_COMMENT_SUCCESS); + } + + @GetMapping("/{postId}") + @ResponseStatus(HttpStatus.OK) + public ApiResponse getCommentByPostId(@PathVariable final Long postId) { + CommentListResponseDto commentsByPostId = commentService.getCommentsByPostId(postId); + return ApiResponse.success(SuccessStatus.READ_COMMENT_SUCCESS, commentsByPostId); + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/PostController.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/PostController.java new file mode 100644 index 0000000..850d200 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/PostController.java @@ -0,0 +1,36 @@ +package sopt.org.ThirdAdvanced.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; +import sopt.org.ThirdAdvanced.common.dto.ApiResponse; +import sopt.org.ThirdAdvanced.controller.dto.request.PostUploadDto; +import sopt.org.ThirdAdvanced.controller.dto.request.UserSignUpDto; +import sopt.org.ThirdAdvanced.controller.dto.response.PostResponseDto; +import sopt.org.ThirdAdvanced.domain.Post; +import sopt.org.ThirdAdvanced.response.SuccessStatus; +import sopt.org.ThirdAdvanced.service.PostService; + +import javax.validation.Valid; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/post") +public class PostController { + + private final PostService postService; + + @PostMapping() + @ResponseStatus(HttpStatus.CREATED) + public ApiResponse uploadPost(@RequestBody @Valid final PostUploadDto request) { + postService.uploadPost(request); + return ApiResponse.success(SuccessStatus.CREATE_POST_SUCCESS); + } + + @GetMapping("/{postId}") + @ResponseStatus(HttpStatus.OK) + public ApiResponse getPostById(@PathVariable final Long postId) { + PostResponseDto findPost = postService.getPostById(postId); + return ApiResponse.success(SuccessStatus.READ_POST_SUCCESS, findPost); + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/UserController.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/UserController.java new file mode 100644 index 0000000..c266000 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/UserController.java @@ -0,0 +1,26 @@ +package sopt.org.ThirdAdvanced.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; +import sopt.org.ThirdAdvanced.common.dto.ApiResponse; +import sopt.org.ThirdAdvanced.controller.dto.request.UserSignUpDto; +import sopt.org.ThirdAdvanced.response.SuccessStatus; +import sopt.org.ThirdAdvanced.service.UserService; + +import javax.validation.Valid; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/user") +public class UserController { + + private final UserService userService; + + @PostMapping("/signup") + @ResponseStatus(HttpStatus.CREATED) + public ApiResponse signup(@RequestBody @Valid final UserSignUpDto request) { + userService.signUp(request); + return ApiResponse.success(SuccessStatus.SIGNUP_SUCCESS); + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/request/CommentUploadDto.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/request/CommentUploadDto.java new file mode 100644 index 0000000..dd84e2e --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/request/CommentUploadDto.java @@ -0,0 +1,21 @@ +package sopt.org.ThirdAdvanced.controller.dto.request; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +@Getter +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class CommentUploadDto { + @NotNull + private Long userId; + + @NotNull + private Long postId; + + @NotBlank + private String content; +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/request/PostUploadDto.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/request/PostUploadDto.java new file mode 100644 index 0000000..ed9b3c6 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/request/PostUploadDto.java @@ -0,0 +1,22 @@ +package sopt.org.ThirdAdvanced.controller.dto.request; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +@Getter +@AllArgsConstructor(access = AccessLevel.PRIVATE) //requestDto는 클라이언트에게 받은 그대로를 가져와야하므로 다른 곳에서 생성되지 않도록 접근 제어 private +public class PostUploadDto { + + @NotNull // NotBlank로 걸면 " "(공백) 검사까지 해야하는데 타입이 String이 아니라 Long이므로 에러남 ! + private Long userId; // 현재는 토큰 개념이 없으므로 클라이언트가 해당 유저 Id를 직접 보내준다고 가정 + + @NotBlank + private String title; + + private String content; +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/request/UserSignUpDto.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/request/UserSignUpDto.java new file mode 100644 index 0000000..3a8292a --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/request/UserSignUpDto.java @@ -0,0 +1,30 @@ +package sopt.org.ThirdAdvanced.controller.dto.request; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +@Getter +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class UserSignUpDto { + @Email(message = "이메일 형식에 맞지 않습니다") + private String email; + + @NotBlank + private String name; + + @NotBlank + @Pattern(regexp = "^[가-힣a-zA-Z]{2,10}$", message = "닉네임 형식에 맞지 않습니다") + private String nickname; + + @NotBlank + @Pattern( + regexp="^\\d{3}-\\d{3,4}-\\d{4}$", + message = "올바른 핸드폰 번호 형식이어야 합니다" + ) + private String phoneNumber; +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/response/CommentListResponseDto.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/response/CommentListResponseDto.java new file mode 100644 index 0000000..4802dfd --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/response/CommentListResponseDto.java @@ -0,0 +1,31 @@ +package sopt.org.ThirdAdvanced.controller.dto.response; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import sopt.org.ThirdAdvanced.domain.Comment; +import sopt.org.ThirdAdvanced.domain.Post; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@Getter +@NoArgsConstructor(access = AccessLevel.PRIVATE) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class CommentListResponseDto { + + private PostResponseDto post; + private List commentList = new ArrayList<>(); + + public static CommentListResponseDto of (Post post, List comments) { + PostResponseDto postDto = PostResponseDto.of(post); + List commentDtos = comments.stream() + .map(CommentResponseDto::of) + .collect(Collectors.toList()); + + return new CommentListResponseDto(postDto, commentDtos); + + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/response/CommentResponseDto.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/response/CommentResponseDto.java new file mode 100644 index 0000000..e04a05f --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/response/CommentResponseDto.java @@ -0,0 +1,28 @@ +package sopt.org.ThirdAdvanced.controller.dto.response; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import sopt.org.ThirdAdvanced.domain.Comment; +import sopt.org.ThirdAdvanced.domain.Post; + +import java.time.LocalDateTime; + +@Getter +@NoArgsConstructor(access = AccessLevel.PRIVATE) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class CommentResponseDto { + + private Long id; + private String authorNickname; + private String authorEmail; + private String content; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; + + public static CommentResponseDto of (Comment comment) { + return new CommentResponseDto(comment.getId(), comment.getUser().getNickname(), comment.getUser().getEmail() + ,comment.getContent(), comment.getCreatedAt(), comment.getModifiedAt()); + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/response/PostResponseDto.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/response/PostResponseDto.java new file mode 100644 index 0000000..06f79dd --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/controller/dto/response/PostResponseDto.java @@ -0,0 +1,27 @@ +package sopt.org.ThirdAdvanced.controller.dto.response; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import sopt.org.ThirdAdvanced.domain.Post; + +import java.time.LocalDateTime; + + +@Getter +@NoArgsConstructor(access = AccessLevel.PRIVATE) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class PostResponseDto { + private Long id; + private String author; + private String title; + private String content; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; + + public static PostResponseDto of(Post findPost) { + return new PostResponseDto(findPost.getId(), findPost.getUser().getNickname(), findPost.getTitle() + , findPost.getContent(), findPost.getCreatedAt(), findPost.getModifiedAt()); + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/domain/Comment.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/domain/Comment.java new file mode 100644 index 0000000..0b6a947 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/domain/Comment.java @@ -0,0 +1,37 @@ +package sopt.org.ThirdAdvanced.domain; + +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import sopt.org.ThirdAdvanced.common.domain.BaseEntity; + +import javax.persistence.*; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Comment extends BaseEntity { + + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Id + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "post_id") + private Post post; + + @Column(nullable = false) + private String content; + + @Builder + public Comment(User user, Post post, String content) { + this.user = user; + this.post = post; + this.content = content; + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/domain/Post.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/domain/Post.java new file mode 100644 index 0000000..89fd0fb --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/domain/Post.java @@ -0,0 +1,36 @@ +package sopt.org.ThirdAdvanced.domain; + +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import sopt.org.ThirdAdvanced.common.domain.BaseEntity; + +import javax.persistence.*; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Post extends BaseEntity { + + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Id + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + @Column(nullable = false) + private String title; + + @Column + private String content; + + @Builder + public Post(User user, String title, String content) { + this.user = user; + this.title = title; + this.content = content; + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/domain/User.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/domain/User.java new file mode 100644 index 0000000..8f6b64f --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/domain/User.java @@ -0,0 +1,42 @@ +package sopt.org.ThirdAdvanced.domain; + +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import sopt.org.ThirdAdvanced.common.domain.BaseEntity; + +import javax.persistence.*; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class User extends BaseEntity { + + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Id + private Long id; + + @Column(nullable = false) + private String name; + + @Column(nullable = false) + private String nickname; + + @Column(name = "phone_number") + private String phoneNumber; + + @Column + private String email; + + @Builder + public User(String name, String nickname, String phoneNumber, String email) { + this.name = name; + this.nickname = nickname; + this.phoneNumber = phoneNumber; + this.email = email; + } + + + +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/exception/CustomException.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/exception/CustomException.java new file mode 100644 index 0000000..d9bbd0c --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/exception/CustomException.java @@ -0,0 +1,18 @@ +package sopt.org.ThirdAdvanced.exception; + +import lombok.Getter; +import sopt.org.ThirdAdvanced.response.FailStatus; + +@Getter +public class CustomException extends RuntimeException { + private final FailStatus failStatus; + + public CustomException(FailStatus failStatus) { + super(failStatus.getMessage()); + this.failStatus = failStatus; + } + + public int getStatusCode() { + return this.failStatus.getStatusCode(); + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/infrastructure/CommentRepository.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/infrastructure/CommentRepository.java new file mode 100644 index 0000000..980081c --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/infrastructure/CommentRepository.java @@ -0,0 +1,10 @@ +package sopt.org.ThirdAdvanced.infrastructure; + +import org.springframework.data.repository.CrudRepository; +import sopt.org.ThirdAdvanced.domain.Comment; + +import java.util.List; + +public interface CommentRepository extends CrudRepository { + List findByPostId(Long postId); +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/infrastructure/PostRepository.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/infrastructure/PostRepository.java new file mode 100644 index 0000000..fabd3c0 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/infrastructure/PostRepository.java @@ -0,0 +1,7 @@ +package sopt.org.ThirdAdvanced.infrastructure; + +import org.springframework.data.repository.CrudRepository; +import sopt.org.ThirdAdvanced.domain.Post; + +public interface PostRepository extends CrudRepository { +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/infrastructure/UserRepository.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/infrastructure/UserRepository.java new file mode 100644 index 0000000..37484b2 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/infrastructure/UserRepository.java @@ -0,0 +1,10 @@ +package sopt.org.ThirdAdvanced.infrastructure; + +import org.springframework.data.repository.CrudRepository; +import sopt.org.ThirdAdvanced.domain.User; + +import java.util.Optional; + +public interface UserRepository extends CrudRepository { + boolean existsByNickname(String nickname); +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/response/FailStatus.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/response/FailStatus.java new file mode 100644 index 0000000..d16cf73 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/response/FailStatus.java @@ -0,0 +1,45 @@ +package sopt.org.ThirdAdvanced.response; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public enum FailStatus { + + /** + *400 BAD_REQUEST + */ + VALIDATION_EXCEPTION(HttpStatus.BAD_REQUEST, "잘못된 요청입니다."), + VALIDATION_REQUEST_MISSING_EXCEPTION(HttpStatus.BAD_REQUEST, "요청값이 입력되지 않았습니다."), + + /** + * 404 NOT FOUND + */ + NOT_FOUND_POST_EXCEPTION(HttpStatus.NOT_FOUND, "해당 게시물을 찾을 수 없습니다."), + NOT_FOUND_USER_EXCEPTION(HttpStatus.NOT_FOUND, "해당 유저를 찾을 수 없습니다."), + + /** + *409 CONFLICT + */ + CONFLICT_EMAIL_EXCEPTION(HttpStatus.CONFLICT, "이미 등록된 이메일입니다."), + CONFLICT_NICKNAME_EXCEPTION(HttpStatus.CONFLICT, "이미 등록된 닉네임입니다."), + + /** + *500 SERVER_ERROR + */ + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "예상치 못한 서버 에러가 발생했습니다."), + BAD_GATEWAY_EXCEPTION(HttpStatus.BAD_GATEWAY, "일시적인 에러가 발생하였습니다.\n잠시 후 다시 시도해주세요!"), + SERVICE_UNAVAILABLE_EXCEPTION(HttpStatus.SERVICE_UNAVAILABLE, "현재 점검 중입니다.\n잠시 후 다시 시도해주세요!"), + ; + + private final HttpStatus httpStatus; + private final String message; + + public int getStatusCode() { + return this.httpStatus.value(); + } +} + diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/response/SuccessStatus.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/response/SuccessStatus.java new file mode 100644 index 0000000..a751495 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/response/SuccessStatus.java @@ -0,0 +1,40 @@ +package sopt.org.ThirdAdvanced.response; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public enum SuccessStatus { + + /** + * 200 OK + */ + READ_USER_SUCCESS(HttpStatus.OK, "유저 조회 성공"), + READ_POST_SUCCESS(HttpStatus.OK, "해당하는 게시물을 조회 성공하였습니다."), + READ_COMMENT_SUCCESS(HttpStatus.OK, "게시물에 달린 댓글들을 조회 성공하였습니다."), + + /** + * 201 CREATE + */ + SIGNUP_SUCCESS(HttpStatus.CREATED, "회원가입이 완료되었습니다."), + CREATE_POST_SUCCESS(HttpStatus.CREATED, "게시물 생성이 완료되었습니다."), + CREATE_COMMENT_SUCCESS(HttpStatus.CREATED, "댓글 생성이 완료되었습니다."), + + + /** + * 204 NO_CONTENT + */ + NO_CONTENT_COMMENT(HttpStatus.NO_CONTENT, "해당 게시물에 달린 댓글이 없습니다.") + ; + + private final HttpStatus httpStatus; + private final String message; + + public int getStatusCode() { + return this.httpStatus.value(); + } +} + diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/CommentService.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/CommentService.java new file mode 100644 index 0000000..afed9f0 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/CommentService.java @@ -0,0 +1,12 @@ +package sopt.org.ThirdAdvanced.service; + +import sopt.org.ThirdAdvanced.controller.dto.request.CommentUploadDto; +import sopt.org.ThirdAdvanced.controller.dto.response.CommentListResponseDto; + +public interface CommentService { + //* 특정 게시물의 댓글 생성 + void uploadComment(CommentUploadDto commentUploadDto); + + //* 특정 게시물의 댓글들 조회 + CommentListResponseDto getCommentsByPostId(Long postId); +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/Impl/CommentServiceImpl.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/Impl/CommentServiceImpl.java new file mode 100644 index 0000000..10ae36e --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/Impl/CommentServiceImpl.java @@ -0,0 +1,60 @@ +package sopt.org.ThirdAdvanced.service.Impl; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import sopt.org.ThirdAdvanced.controller.dto.request.CommentUploadDto; +import sopt.org.ThirdAdvanced.controller.dto.response.CommentListResponseDto; +import sopt.org.ThirdAdvanced.domain.Comment; +import sopt.org.ThirdAdvanced.domain.Post; +import sopt.org.ThirdAdvanced.domain.User; +import sopt.org.ThirdAdvanced.exception.CustomException; +import sopt.org.ThirdAdvanced.infrastructure.CommentRepository; +import sopt.org.ThirdAdvanced.infrastructure.PostRepository; +import sopt.org.ThirdAdvanced.infrastructure.UserRepository; +import sopt.org.ThirdAdvanced.response.FailStatus; +import sopt.org.ThirdAdvanced.service.CommentService; + +import java.util.List; + +@Service +@RequiredArgsConstructor +public class CommentServiceImpl implements CommentService { + + private final CommentRepository commentRepository; + private final UserRepository userRepository; + private final PostRepository postRepository; + + @Override + @Transactional + public void uploadComment(CommentUploadDto commentUploadDto) { + User user = findUser(commentUploadDto.getUserId()); + Post post = findPost(commentUploadDto.getPostId()); + + Comment newComment = Comment.builder() + .user(user) + .post(post) + .content(commentUploadDto.getContent()) + .build(); + + commentRepository.save(newComment); + } + + @Override + @Transactional + public CommentListResponseDto getCommentsByPostId(Long postId) { + Post post = findPost(postId); + List byPostId = commentRepository.findByPostId(postId); + return CommentListResponseDto.of(post, byPostId); + } + + private User findUser(Long userId) { + User findUser = userRepository.findById(userId).orElseThrow(() -> new CustomException(FailStatus.NOT_FOUND_USER_EXCEPTION)); + return findUser; + } + + private Post findPost(Long postId) { + Post findPost = postRepository.findById(postId).orElseThrow(() -> new CustomException(FailStatus.NOT_FOUND_POST_EXCEPTION)); + return findPost; + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/Impl/PostServiceImpl.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/Impl/PostServiceImpl.java new file mode 100644 index 0000000..15a97fd --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/Impl/PostServiceImpl.java @@ -0,0 +1,49 @@ +package sopt.org.ThirdAdvanced.service.Impl; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import sopt.org.ThirdAdvanced.controller.dto.request.PostUploadDto; +import sopt.org.ThirdAdvanced.controller.dto.response.PostResponseDto; +import sopt.org.ThirdAdvanced.domain.Post; +import sopt.org.ThirdAdvanced.domain.User; +import sopt.org.ThirdAdvanced.exception.CustomException; +import sopt.org.ThirdAdvanced.infrastructure.PostRepository; +import sopt.org.ThirdAdvanced.infrastructure.UserRepository; +import sopt.org.ThirdAdvanced.response.FailStatus; +import sopt.org.ThirdAdvanced.service.PostService; + +@Service +@RequiredArgsConstructor +public class PostServiceImpl implements PostService { + + private final PostRepository postRepository; + private final UserRepository userRepository; + + @Override + @Transactional + public void uploadPost(PostUploadDto postUploadDto) { + User findUser = findByUser(postUploadDto.getUserId()); + + Post newPost = Post.builder() + .user(findUser) + .title(postUploadDto.getTitle()) + .content(postUploadDto.getContent()) + .build(); + + postRepository.save(newPost); + } + + @Override + @Transactional + public PostResponseDto getPostById(Long postId) { + Post findPost = postRepository.findById(postId).orElseThrow(() -> new CustomException(FailStatus.NOT_FOUND_POST_EXCEPTION)); + + return PostResponseDto.of(findPost); + } + + private User findByUser(Long userId) { + User findUser = userRepository.findById(userId).orElseThrow(() -> new CustomException(FailStatus.NOT_FOUND_USER_EXCEPTION)); + return findUser; + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/Impl/UserServiceImpl.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/Impl/UserServiceImpl.java new file mode 100644 index 0000000..e417096 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/Impl/UserServiceImpl.java @@ -0,0 +1,42 @@ +package sopt.org.ThirdAdvanced.service.Impl; + +import lombok.RequiredArgsConstructor; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import sopt.org.ThirdAdvanced.controller.dto.request.UserSignUpDto; +import sopt.org.ThirdAdvanced.domain.User; +import sopt.org.ThirdAdvanced.exception.CustomException; +import sopt.org.ThirdAdvanced.infrastructure.UserRepository; +import sopt.org.ThirdAdvanced.response.FailStatus; +import sopt.org.ThirdAdvanced.service.UserService; + +@Service +@RequiredArgsConstructor +public class UserServiceImpl implements UserService { + private final UserRepository userRepository; + + @Override + @Transactional + public void signUp(UserSignUpDto request) { + String nickname = request.getNickname(); + if (userRepository.existsByNickname(nickname)) { + throw new DuplicateKeyException(FailStatus.CONFLICT_NICKNAME_EXCEPTION.getMessage()); + } + + User user = User.builder() + .name(request.getName()) + .nickname(request.getNickname()) + .email(request.getEmail()) + .phoneNumber(request.getPhoneNumber()) + .build(); + + userRepository.save(user); + } + + @Transactional + public User findById(Long userId) { + User findUser = userRepository.findById(userId).orElseThrow(() -> new CustomException(FailStatus.NOT_FOUND_USER_EXCEPTION)); + return findUser; + } +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/PostService.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/PostService.java new file mode 100644 index 0000000..88b6637 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/PostService.java @@ -0,0 +1,14 @@ +package sopt.org.ThirdAdvanced.service; + +import sopt.org.ThirdAdvanced.controller.dto.request.PostUploadDto; +import sopt.org.ThirdAdvanced.controller.dto.response.PostResponseDto; +import sopt.org.ThirdAdvanced.domain.Post; + +public interface PostService { + + //* 게시물 생성 + void uploadPost(PostUploadDto postUploadDto); + + //* 게시물 조회 + PostResponseDto getPostById(Long postId); +} diff --git a/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/UserService.java b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/UserService.java new file mode 100644 index 0000000..b4977a0 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/main/java/sopt/org/ThirdAdvanced/service/UserService.java @@ -0,0 +1,12 @@ +package sopt.org.ThirdAdvanced.service; + +import sopt.org.ThirdAdvanced.controller.dto.request.UserSignUpDto; +import sopt.org.ThirdAdvanced.domain.User; + +import java.util.Optional; + +public interface UserService { + + //* 유저 회원가입 + void signUp(UserSignUpDto userSignUpDto); +} diff --git a/week3/Advanced/ThirdAdvanced/src/test/java/sopt/org/ThirdAdvanced/ThirdAdvancedApplicationTests.java b/week3/Advanced/ThirdAdvanced/src/test/java/sopt/org/ThirdAdvanced/ThirdAdvancedApplicationTests.java new file mode 100644 index 0000000..55da673 --- /dev/null +++ b/week3/Advanced/ThirdAdvanced/src/test/java/sopt/org/ThirdAdvanced/ThirdAdvancedApplicationTests.java @@ -0,0 +1,13 @@ +package sopt.org.ThirdAdvanced; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ThirdAdvancedApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/week3/Basic/ThirdSeminar/.gitignore b/week3/Basic/ThirdSeminar/.gitignore new file mode 100644 index 0000000..6e5a248 --- /dev/null +++ b/week3/Basic/ThirdSeminar/.gitignore @@ -0,0 +1,39 @@ +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/ + +resources diff --git a/week3/Basic/ThirdSeminar/build.gradle b/week3/Basic/ThirdSeminar/build.gradle new file mode 100644 index 0000000..cabf5f3 --- /dev/null +++ b/week3/Basic/ThirdSeminar/build.gradle @@ -0,0 +1,35 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '2.7.11' + id 'io.spring.dependency-management' version '1.0.15.RELEASE' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '11' + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + // mysql --version + implementation 'mysql:mysql-connector-java:8.0.32' + + implementation 'org.springframework.boot:spring-boot-starter-validation' + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/week3/Basic/ThirdSeminar/gradle/wrapper/gradle-wrapper.jar b/week3/Basic/ThirdSeminar/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/week3/Basic/ThirdSeminar/gradle/wrapper/gradle-wrapper.jar differ diff --git a/week3/Basic/ThirdSeminar/gradle/wrapper/gradle-wrapper.properties b/week3/Basic/ThirdSeminar/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..774fae8 --- /dev/null +++ b/week3/Basic/ThirdSeminar/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/week3/Basic/ThirdSeminar/gradlew b/week3/Basic/ThirdSeminar/gradlew new file mode 100755 index 0000000..a69d9cb --- /dev/null +++ b/week3/Basic/ThirdSeminar/gradlew @@ -0,0 +1,240 @@ +#!/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/master/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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 + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# 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/week3/Basic/ThirdSeminar/gradlew.bat b/week3/Basic/ThirdSeminar/gradlew.bat new file mode 100644 index 0000000..53a6b23 --- /dev/null +++ b/week3/Basic/ThirdSeminar/gradlew.bat @@ -0,0 +1,91 @@ +@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=. +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/week3/Basic/ThirdSeminar/settings.gradle b/week3/Basic/ThirdSeminar/settings.gradle new file mode 100644 index 0000000..397b799 --- /dev/null +++ b/week3/Basic/ThirdSeminar/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'ThirdSeminar' diff --git a/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/ThirdSeminarApplication.java b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/ThirdSeminarApplication.java new file mode 100644 index 0000000..1223b37 --- /dev/null +++ b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/ThirdSeminarApplication.java @@ -0,0 +1,13 @@ +package com.example.ThirdSeminar; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ThirdSeminarApplication { + + public static void main(String[] args) { + SpringApplication.run(ThirdSeminarApplication.class, args); + } + +} diff --git a/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/common/advice/ControllerExceptionAdvice.java b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/common/advice/ControllerExceptionAdvice.java new file mode 100644 index 0000000..a9b8915 --- /dev/null +++ b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/common/advice/ControllerExceptionAdvice.java @@ -0,0 +1,22 @@ +package com.example.ThirdSeminar.common.advice; + +import com.example.ThirdSeminar.common.dto.ApiResponseDto; +import com.example.ThirdSeminar.exception.ErrorStatus; +import org.springframework.http.HttpStatus; +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; + +@RestControllerAdvice +public class ControllerExceptionAdvice { + + /* + * 400 BAD_REQUEST + */ + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(MethodArgumentNotValidException.class) + protected ApiResponseDto handleMethodArgumentNotValidException(final MethodArgumentNotValidException e) { + return ApiResponseDto.error(ErrorStatus.VALIDATION_REQUEST_MISSING_EXCEPTION); + } +} diff --git a/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/common/dto/ApiResponseDto.java b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/common/dto/ApiResponseDto.java new file mode 100644 index 0000000..e8a7de5 --- /dev/null +++ b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/common/dto/ApiResponseDto.java @@ -0,0 +1,30 @@ +package com.example.ThirdSeminar.common.dto; + +import com.example.ThirdSeminar.exception.ErrorStatus; +import com.example.ThirdSeminar.exception.SuccessStatus; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class ApiResponseDto { + + private final int code; + private final String message; + private T data; + + public static ApiResponseDto success(SuccessStatus successStatus) { + return new ApiResponseDto<>(successStatus.getHttpStatus().value(), successStatus.getMessage()); + } + + public static ApiResponseDto success(SuccessStatus successStatus, T data) { + return new ApiResponseDto(successStatus.getHttpStatus().value(), successStatus.getMessage(), data); + } + + public static ApiResponseDto error(ErrorStatus errorStatus) { + return new ApiResponseDto<>(errorStatus.getHttpStatus().value(), errorStatus.getMessage()); + } +} diff --git a/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/controller/UserController.java b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/controller/UserController.java new file mode 100644 index 0000000..7759f68 --- /dev/null +++ b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/controller/UserController.java @@ -0,0 +1,28 @@ +package com.example.ThirdSeminar.controller; + +import com.example.ThirdSeminar.common.dto.ApiResponseDto; +import com.example.ThirdSeminar.controller.dto.user.request.UserRequestDto; +import com.example.ThirdSeminar.controller.dto.user.response.UserResponseDto; +import com.example.ThirdSeminar.exception.SuccessStatus; +import com.example.ThirdSeminar.service.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import javax.validation.Valid; + +@RestController +@RequiredArgsConstructor +public class UserController { + private final UserService userService; + + @PostMapping("/user/signup") + @ResponseStatus(HttpStatus.CREATED) + public ApiResponseDto create(@RequestBody @Valid final UserRequestDto requestDto) { + return ApiResponseDto.success(SuccessStatus.SIGNUP_SUCCESS, userService.create(requestDto)); + } + +} diff --git a/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/controller/dto/user/request/UserRequestDto.java b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/controller/dto/user/request/UserRequestDto.java new file mode 100644 index 0000000..b91baf4 --- /dev/null +++ b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/controller/dto/user/request/UserRequestDto.java @@ -0,0 +1,30 @@ +package com.example.ThirdSeminar.controller.dto.user.request; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; + +@Getter +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class UserRequestDto { + + @Email(message = "이메일 형식에 맞지 않습니다") + @NotNull + private String email; + + @NotBlank + @Pattern(regexp = "^[가-힣a-zA-Z]{2,10}$", message = "닉네임 형식에 맞지 않습니다.") + private String nickname; + + @NotBlank + @Pattern( + regexp="(?=.*[0-9])(?=.*[a-zA-Z])(?=.*\\W)(?=\\S+$).{8,20}", + message = "비밀번호는 영문 대,소문자와 숫자, 특수기호가 적어도 1개 이상씩 포함된 8자 ~ 20자의 비밀번호여야 합니다." + ) + private String password; +} \ No newline at end of file diff --git a/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/controller/dto/user/response/UserResponseDto.java b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/controller/dto/user/response/UserResponseDto.java new file mode 100644 index 0000000..063f0d4 --- /dev/null +++ b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/controller/dto/user/response/UserResponseDto.java @@ -0,0 +1,17 @@ +package com.example.ThirdSeminar.controller.dto.user.response; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class UserResponseDto { + + private Long userId; + private String nickname; + + public static UserResponseDto of(Long userId, String nickname) { + return new UserResponseDto(userId, nickname); + } +} diff --git a/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/domain/User.java b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/domain/User.java new file mode 100644 index 0000000..b7b5c50 --- /dev/null +++ b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/domain/User.java @@ -0,0 +1,32 @@ +package com.example.ThirdSeminar.domain; + +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String nickname; + @Column(nullable = false) + private String email; + @Column(nullable = false) + private String password; + + @Builder + private User(String nickname, String email, String password) { + this.nickname = nickname; + this.email = email; + this.password = password; + } +} diff --git a/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/exception/ErrorStatus.java b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/exception/ErrorStatus.java new file mode 100644 index 0000000..3da7d9e --- /dev/null +++ b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/exception/ErrorStatus.java @@ -0,0 +1,35 @@ +package com.example.ThirdSeminar.exception; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public enum ErrorStatus { + + /* + BAD_REQUEST + */ + VALIDATION_EXCEPTION(HttpStatus.BAD_REQUEST, "잘못된 요청입니다."), + VALIDATION_REQUEST_MISSING_EXCEPTION(HttpStatus.BAD_REQUEST, "요청값이 입력되지 않았습니다."), + + /* + CONFLICT + */ + CONFLICT_EMAIL_EXCEPTION(HttpStatus.CONFLICT, "이미 등록된 이메일입니다."), + CONFLICT_NICKNAME_EXCEPTION(HttpStatus.CONFLICT, "이미 등록된 닉네임입니다."), + + /* + SERVER_ERROR + */ + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "예상치 못한 서버 에러가 발생했습니다."), + BAD_GATEWAY_EXCEPTION(HttpStatus.BAD_GATEWAY, "일시적인 에러가 발생하였습니다.\n잠시 후 다시 시도해주세요!"), + SERVICE_UNAVAILABLE_EXCEPTION(HttpStatus.SERVICE_UNAVAILABLE, "현재 점검 중입니다.\n잠시 후 다시 시도해주세요!"), + ; + + private final HttpStatus httpStatus; + private final String message; +} + diff --git a/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/exception/SuccessStatus.java b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/exception/SuccessStatus.java new file mode 100644 index 0000000..5937c1b --- /dev/null +++ b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/exception/SuccessStatus.java @@ -0,0 +1,21 @@ +package com.example.ThirdSeminar.exception; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public enum SuccessStatus { + + /* + user + */ + SIGNUP_SUCCESS(HttpStatus.CREATED, "회원가입이 완료되었습니다."), + ; + + private final HttpStatus httpStatus; + private final String message; +} + diff --git a/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/infrastructure/UserRepository.java b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/infrastructure/UserRepository.java new file mode 100644 index 0000000..cca1bff --- /dev/null +++ b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/infrastructure/UserRepository.java @@ -0,0 +1,8 @@ +package com.example.ThirdSeminar.infrastructure; + +import com.example.ThirdSeminar.domain.User; +import org.springframework.data.repository.Repository; + +public interface UserRepository extends Repository { + void save(User user); +} diff --git a/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/service/UserService.java b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/service/UserService.java new file mode 100644 index 0000000..dea18aa --- /dev/null +++ b/week3/Basic/ThirdSeminar/src/main/java/com/example/ThirdSeminar/service/UserService.java @@ -0,0 +1,27 @@ +package com.example.ThirdSeminar.service; + +import com.example.ThirdSeminar.controller.dto.user.request.UserRequestDto; +import com.example.ThirdSeminar.controller.dto.user.response.UserResponseDto; +import com.example.ThirdSeminar.domain.User; +import com.example.ThirdSeminar.infrastructure.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class UserService { + private final UserRepository userRepository; + + @Transactional + public UserResponseDto create(UserRequestDto requestDto) { + User user = User.builder() + .email(requestDto.getEmail()) + .nickname(requestDto.getNickname()) + .password(requestDto.getPassword()) + .build(); + + userRepository.save(user); + return UserResponseDto.of(user.getId(), user.getNickname()); + } +} diff --git a/week3/Basic/ThirdSeminar/src/test/java/com/example/ThirdSeminar/ThirdSeminarApplicationTests.java b/week3/Basic/ThirdSeminar/src/test/java/com/example/ThirdSeminar/ThirdSeminarApplicationTests.java new file mode 100644 index 0000000..3b3acdf --- /dev/null +++ b/week3/Basic/ThirdSeminar/src/test/java/com/example/ThirdSeminar/ThirdSeminarApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.ThirdSeminar; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ThirdSeminarApplicationTests { + + @Test + void contextLoads() { + } + +}