diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..0c2d1e48 --- /dev/null +++ b/.gitignore @@ -0,0 +1,68 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# ------------- spring ------------- +.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/ + +### Mac ### +.DS_Store + +.env + +gradle.properties \ No newline at end of file diff --git a/hackathon/.gitignore b/hackathon/.gitignore new file mode 100644 index 00000000..c2065bc2 --- /dev/null +++ b/hackathon/.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/hackathon/build.gradle b/hackathon/build.gradle new file mode 100644 index 00000000..b8353fe5 --- /dev/null +++ b/hackathon/build.gradle @@ -0,0 +1,33 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '2.7.9' + id 'io.spring.dependency-management' version '1.0.15.RELEASE' +} + +group = 'com.techeer' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '11' + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation group: 'io.springfox', name: 'springfox-boot-starter', version: '3.0.0' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/hackathon/docker-compose.yml b/hackathon/docker-compose.yml new file mode 100644 index 00000000..a6f3823c --- /dev/null +++ b/hackathon/docker-compose.yml @@ -0,0 +1,18 @@ +version: '3' + +volumes: + db-data: + +services: + mysql: + container_name: mysql + image: mysql:latest + expose: + - "3306" + environment: + MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} + MYSQL_DATABASE: ${MYSQL_DATABASE} + ports: + - "3306:3306" + volumes: + - db-data:/msql \ No newline at end of file diff --git a/hackathon/gradle/wrapper/gradle-wrapper.properties b/hackathon/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..070cb702 --- /dev/null +++ b/hackathon/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-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/hackathon/gradlew b/hackathon/gradlew new file mode 100755 index 00000000..a69d9cb6 --- /dev/null +++ b/hackathon/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/hackathon/gradlew.bat b/hackathon/gradlew.bat new file mode 100644 index 00000000..f127cfd4 --- /dev/null +++ b/hackathon/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/hackathon/settings.gradle b/hackathon/settings.gradle new file mode 100644 index 00000000..d6cc5f66 --- /dev/null +++ b/hackathon/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'hackathon' diff --git a/hackathon/src/main/java/com/techeer/hackathon/HackathonApplication.java b/hackathon/src/main/java/com/techeer/hackathon/HackathonApplication.java new file mode 100644 index 00000000..26dc8ef3 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/HackathonApplication.java @@ -0,0 +1,13 @@ +package com.techeer.hackathon; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class HackathonApplication { + + public static void main(String[] args) { + SpringApplication.run(HackathonApplication.class, args); + } + +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/controller/RestaurantController.java b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/controller/RestaurantController.java new file mode 100644 index 00000000..b58a1e13 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/controller/RestaurantController.java @@ -0,0 +1,57 @@ +package com.techeer.hackathon.domain.restaurant.controller; + +import com.techeer.hackathon.domain.restaurant.dto.RestaurantChange; +import com.techeer.hackathon.domain.restaurant.dto.RestaurantCreate; +import com.techeer.hackathon.domain.restaurant.dto.RestaurantResponse; +import com.techeer.hackathon.domain.restaurant.service.RestaurantService; +import com.techeer.hackathon.global.result.ResultCode; +import com.techeer.hackathon.global.result.ResultResponse; +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("api/v1/restaurant") +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public class RestaurantController { + + private final RestaurantService restaurantService; + + @PostMapping + public ResponseEntity registerRestaurant( + @RequestBody RestaurantCreate request) { + restaurantService.createRestaurant(request); + return ResponseEntity.ok(ResultResponse.of(ResultCode.RESTAURANT_CREATE_SUCCESS)); + } + + @PatchMapping + public ResponseEntity changeRestaurantCategory( + @RequestBody RestaurantChange request) { + restaurantService.changeCategory(request); + return ResponseEntity.ok(ResultResponse.of(ResultCode.CHANGE_CATEGORY_SUCCESS)); + } + + @GetMapping("/all") + public ResponseEntity getAllRestaurantByCategories( + @RequestParam String categories) { + List restaurants = restaurantService.getRestaurantResponse(categories); + + return ResponseEntity.ok(ResultResponse.of(ResultCode.GET_ALL_RESTAURANTS_SUCCESS, restaurants)); + } + + @PatchMapping("/{id}") + public ResponseEntity deleteRestaurant( + @PathVariable Long id) { + restaurantService.deleteRestaurant(id); + return ResponseEntity.ok(ResultResponse.of(ResultCode.DELETE_RESTAURANTS_SUCCESS)); + } + + @GetMapping("/{id}") + public ResponseEntity getRestaurant( + @PathVariable Long id) { + return ResponseEntity.ok(ResultResponse.of(ResultCode.GET_RESTAURANTS_SUCCESS, restaurantService.getRestaurant(id))); + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/dto/RestaurantChange.java b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/dto/RestaurantChange.java new file mode 100644 index 00000000..8e016dcc --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/dto/RestaurantChange.java @@ -0,0 +1,24 @@ +package com.techeer.hackathon.domain.restaurant.dto; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.techeer.hackathon.domain.restaurant.entity.RestaurantCategory; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class RestaurantChange { + private Long id; + private RestaurantCategory category; + + @JsonCreator + public RestaurantChange(@JsonProperty("id") Long id, @JsonProperty("category") String category) { + this.id = id; + if(!RestaurantCategory.isValidCategory(category.toUpperCase())) this.category = null; + else this.category = RestaurantCategory.valueOf(category.toUpperCase()); + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/dto/RestaurantCreate.java b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/dto/RestaurantCreate.java new file mode 100644 index 00000000..898a2a08 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/dto/RestaurantCreate.java @@ -0,0 +1,24 @@ +package com.techeer.hackathon.domain.restaurant.dto; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.techeer.hackathon.domain.restaurant.entity.RestaurantCategory; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class RestaurantCreate { + private RestaurantCategory category; + private String name; + + @JsonCreator + public RestaurantCreate(@JsonProperty("name") String name, @JsonProperty("category") String category) { + this.name = name; + if(!RestaurantCategory.isValidCategory(category.toUpperCase())) this.category = null; + else this.category = RestaurantCategory.valueOf(category.toUpperCase()); + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/dto/RestaurantResponse.java b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/dto/RestaurantResponse.java new file mode 100644 index 00000000..4d0b0232 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/dto/RestaurantResponse.java @@ -0,0 +1,18 @@ +package com.techeer.hackathon.domain.restaurant.dto; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; + +import java.time.LocalDateTime; + + +@Getter +@Builder +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class RestaurantResponse { + String name; + String category; + LocalDateTime createdAt; +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/entity/Restaurant.java b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/entity/Restaurant.java new file mode 100644 index 00000000..2318e83a --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/entity/Restaurant.java @@ -0,0 +1,56 @@ +package com.techeer.hackathon.domain.restaurant.entity; + +import com.techeer.hackathon.domain.review.entity.Review; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.DynamicInsert; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.*; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Getter +@Entity +@Table(name = "RESTAURANT") +@DynamicInsert +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@EntityListeners(AuditingEntityListener.class) +public class Restaurant { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + // Review 와 1:N 관계 + @OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, orphanRemoval = true) + private List reviews = new ArrayList<>(); + + @Column(nullable = false, length = 30) + private String name; + + @Enumerated(EnumType.STRING) + @Column(nullable = false) + private RestaurantCategory category; + + @Column(columnDefinition = "boolean default false") + private Boolean isDeleted; + + @CreatedDate + private LocalDateTime createdAt; + + @Builder + public Restaurant( + String name, + RestaurantCategory category) { + this.name = name; + this.category = category; + } + + public void deleteRestaurant() { + this.isDeleted = true; + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/entity/RestaurantCategory.java b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/entity/RestaurantCategory.java new file mode 100644 index 00000000..7db43106 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/entity/RestaurantCategory.java @@ -0,0 +1,30 @@ +package com.techeer.hackathon.domain.restaurant.entity; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public enum RestaurantCategory { + KOREAN_RESTAURANT("한식"), + CHINESE_RESTAURANT("중식"), + JAPANESE_RESTAURANT("일식"); + + private final String category; + + public static Boolean isValidCategory(String category) { + for (RestaurantCategory cat : RestaurantCategory.values()) { + System.out.println(cat.getCategory()); + if(cat.toString().equals(category)) return true; + } + return false; + } + + public static RestaurantCategory getCategory(String category) { + for (RestaurantCategory cat : RestaurantCategory.values()) { + System.out.println(cat.getCategory()); + if(cat.toString().equals(category)) return cat; + } + return null; + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/error/InvalidCategoryException.java b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/error/InvalidCategoryException.java new file mode 100644 index 00000000..f1f88188 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/error/InvalidCategoryException.java @@ -0,0 +1,11 @@ +package com.techeer.hackathon.domain.restaurant.error; + +import com.techeer.hackathon.global.error.exceptions.BusinessException; + +import static com.techeer.hackathon.global.error.ErrorCode.INVALID_CATEGORY_ERROR; + +public class InvalidCategoryException extends BusinessException { + public InvalidCategoryException() { + super(INVALID_CATEGORY_ERROR); + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/error/RestaurantDuplicateException.java b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/error/RestaurantDuplicateException.java new file mode 100644 index 00000000..2b673c8f --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/error/RestaurantDuplicateException.java @@ -0,0 +1,10 @@ +package com.techeer.hackathon.domain.restaurant.error; + +import com.techeer.hackathon.global.error.ErrorCode; +import com.techeer.hackathon.global.error.exceptions.BusinessException; + +public class RestaurantDuplicateException extends BusinessException { + public RestaurantDuplicateException() { + super(ErrorCode.RESTAURANT_DUPLICATION_ERROR); + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/error/RestaurantNotFoundException.java b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/error/RestaurantNotFoundException.java new file mode 100644 index 00000000..36755e5b --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/error/RestaurantNotFoundException.java @@ -0,0 +1,11 @@ +package com.techeer.hackathon.domain.restaurant.error; + +import com.techeer.hackathon.global.error.exceptions.BusinessException; + +import static com.techeer.hackathon.global.error.ErrorCode.RESTAURANT_NOT_FOUND; + +public class RestaurantNotFoundException extends BusinessException { + public RestaurantNotFoundException() { + super(RESTAURANT_NOT_FOUND); + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/mapper/RestaurantMapper.java b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/mapper/RestaurantMapper.java new file mode 100644 index 00000000..9488fb3d --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/mapper/RestaurantMapper.java @@ -0,0 +1,32 @@ +package com.techeer.hackathon.domain.restaurant.mapper; + +import com.techeer.hackathon.domain.restaurant.dto.RestaurantCreate; +import com.techeer.hackathon.domain.restaurant.dto.RestaurantResponse; +import com.techeer.hackathon.domain.restaurant.entity.Restaurant; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.stream.Collectors; + +@Component +public class RestaurantMapper { + public Restaurant toEntity(RestaurantCreate request) { + return Restaurant.builder() + .category(request.getCategory()) + .name(request.getName()) + .build(); + } + + public RestaurantResponse toDto(Restaurant restaurant) { + + return RestaurantResponse.builder() + .category(restaurant.getCategory().name()) + .name(restaurant.getName()) + .createdAt(restaurant.getCreatedAt()) + .build(); + } + + public List toDtoList(List list) { + return list.stream().map(this::toDto).collect(Collectors.toList()); + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/repository/RestaurantRepository.java b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/repository/RestaurantRepository.java new file mode 100644 index 00000000..bcc70980 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/repository/RestaurantRepository.java @@ -0,0 +1,31 @@ +package com.techeer.hackathon.domain.restaurant.repository; + +import com.techeer.hackathon.domain.restaurant.entity.Restaurant; +import com.techeer.hackathon.domain.restaurant.entity.RestaurantCategory; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Optional; + +public interface RestaurantRepository extends JpaRepository { + boolean existsByName(String name); + + @Modifying + @Transactional + @Query("update Restaurant r set r.category = :category where r.id = :id") + void updateCategory(@Param("id") Long id, @Param("category") RestaurantCategory category); + + @Query("SELECT r FROM Restaurant r WHERE r.category IN :categories") + List findByCategory(@Param("categories") List categories); + + @Modifying + @Transactional + @Query("update Restaurant r set r.isDeleted = 1 where r.id = :id") + void softDeleteById(Long id); + + Optional findByName(String restaurantName); +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/service/RestaurantService.java b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/service/RestaurantService.java new file mode 100644 index 00000000..7391d6d8 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/restaurant/service/RestaurantService.java @@ -0,0 +1,63 @@ +package com.techeer.hackathon.domain.restaurant.service; + +import com.techeer.hackathon.domain.restaurant.error.RestaurantNotFoundException; +import com.techeer.hackathon.domain.restaurant.mapper.RestaurantMapper; +import com.techeer.hackathon.domain.restaurant.dto.RestaurantChange; +import com.techeer.hackathon.domain.restaurant.dto.RestaurantCreate; +import com.techeer.hackathon.domain.restaurant.dto.RestaurantResponse; +import com.techeer.hackathon.domain.restaurant.entity.Restaurant; +import com.techeer.hackathon.domain.restaurant.entity.RestaurantCategory; +import com.techeer.hackathon.domain.restaurant.error.InvalidCategoryException; +import com.techeer.hackathon.domain.restaurant.error.RestaurantDuplicateException; +import com.techeer.hackathon.domain.restaurant.repository.RestaurantRepository; +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public class RestaurantService { + private final RestaurantRepository restaurantRepository; + private final RestaurantMapper restaurantMapper; + + public void createRestaurant(RestaurantCreate restaurantCreate) { + if(restaurantRepository.existsByName(restaurantCreate.getName())) { + throw new RestaurantDuplicateException(); + } + if(restaurantCreate.getCategory() == null) { + throw new InvalidCategoryException(); + } + restaurantRepository.save(restaurantMapper.toEntity(restaurantCreate)); + } + + public void changeCategory(RestaurantChange request) { + if(request.getCategory() == null) { + throw new InvalidCategoryException(); + } + restaurantRepository.updateCategory(request.getId(), request.getCategory()); + } + + public List getRestaurantResponse(String categories) { + String[] categoryArray = categories.split(","); + List categoriesList = new ArrayList<>(); + for (String category : categoryArray) { + if(RestaurantCategory.isValidCategory(category)) { + categoriesList.add(RestaurantCategory.getCategory(category)); + } + else throw new InvalidCategoryException(); + } + List restaurants = restaurantRepository.findByCategory(categoriesList); + return restaurantMapper.toDtoList(restaurants); + } + + public void deleteRestaurant(Long id) { + restaurantRepository.softDeleteById(id); + } + + public RestaurantResponse getRestaurant(Long id) { + return restaurantMapper.toDto(restaurantRepository.findById(id).orElseThrow(RestaurantNotFoundException::new)); + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/review/controller/ReviewController.java b/hackathon/src/main/java/com/techeer/hackathon/domain/review/controller/ReviewController.java new file mode 100644 index 00000000..8e31ff4e --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/review/controller/ReviewController.java @@ -0,0 +1,60 @@ +package com.techeer.hackathon.domain.review.controller; + +import com.techeer.hackathon.domain.review.dto.ReviewCreate; +import com.techeer.hackathon.domain.review.dto.ReviewInfo; +import com.techeer.hackathon.domain.review.dto.ReviewUpdateRequest; +import com.techeer.hackathon.domain.review.service.ReviewService; +import com.techeer.hackathon.global.result.ResultCode; +import com.techeer.hackathon.global.result.ResultResponse; +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.PageRequest; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("api/v1/review") +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public class ReviewController { + private final ReviewService reviewService; + + @PostMapping + public ResponseEntity createReview( + @RequestBody ReviewCreate request + ) { + reviewService.createReview(request); + return ResponseEntity.ok(ResultResponse.of(ResultCode.REVIEW_CREATE_SUCCESS)); + } + + @GetMapping("/{id}") + public ResponseEntity getReview( + @PathVariable Long id) { + return ResponseEntity.ok(ResultResponse.of(ResultCode.GET_REVIEW_SUCCESS, reviewService.getReview(id))); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteReview( + @PathVariable Long id) { + reviewService.deleteReview(id); + return ResponseEntity.ok(ResultResponse.of(ResultCode.DELETE_REVIEW_SUCCESS)); + } + + @PatchMapping("/{id}") + public ResponseEntity updateReview( + @RequestBody ReviewUpdateRequest reviewUpdateRequest + ) { + reviewService.updateReview(reviewUpdateRequest); + return ResponseEntity.ok(ResultResponse.of(ResultCode.UPDATE_REVIEW_SUCCESS)); + } + + @GetMapping("/all/{page}") + public ResponseEntity getReviews( + @PathVariable Integer page, @RequestParam(defaultValue = "20") Integer size) { + PageRequest pageRequest = PageRequest.of(page, size); + List reviews = reviewService.getReviews(pageRequest); + return ResponseEntity.ok(ResultResponse.of(ResultCode.GET_ALL_REVIEW_SUCCESS, reviews)); + } + +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/review/dto/ReviewCreate.java b/hackathon/src/main/java/com/techeer/hackathon/domain/review/dto/ReviewCreate.java new file mode 100644 index 00000000..9f58a368 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/review/dto/ReviewCreate.java @@ -0,0 +1,13 @@ +package com.techeer.hackathon.domain.review.dto; + +import lombok.*; + +@Getter +@Builder +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class ReviewCreate { + private String restaurantName; + private String title; + private String content; +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/review/dto/ReviewInfo.java b/hackathon/src/main/java/com/techeer/hackathon/domain/review/dto/ReviewInfo.java new file mode 100644 index 00000000..a15b3149 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/review/dto/ReviewInfo.java @@ -0,0 +1,13 @@ +package com.techeer.hackathon.domain.review.dto; + +import lombok.*; + +@Getter +@Builder +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class ReviewInfo { + private String restaurantName; + private String title; + private String content; +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/review/dto/ReviewUpdateRequest.java b/hackathon/src/main/java/com/techeer/hackathon/domain/review/dto/ReviewUpdateRequest.java new file mode 100644 index 00000000..3e090ebc --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/review/dto/ReviewUpdateRequest.java @@ -0,0 +1,13 @@ +package com.techeer.hackathon.domain.review.dto; + +import lombok.*; + +@Getter +@Builder +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class ReviewUpdateRequest { + private Long id; + private String title; + private String content; +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/review/entity/Review.java b/hackathon/src/main/java/com/techeer/hackathon/domain/review/entity/Review.java new file mode 100644 index 00000000..ba7f3722 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/review/entity/Review.java @@ -0,0 +1,47 @@ +package com.techeer.hackathon.domain.review.entity; + +import com.techeer.hackathon.domain.restaurant.entity.Restaurant; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Getter +@Entity +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Table(name = "REVIEW") +@EntityListeners(AuditingEntityListener.class) +public class Review { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "restaurant_id", nullable = false) + private Restaurant restaurant; + + @Column(nullable = false) + private String title; + + @Column(nullable = false) + private String content; + + @CreatedDate + private LocalDateTime createdAt; + + @Builder + public Review( + Restaurant restaurant, + String title, + String content + ) { + this.restaurant = restaurant; + this.title = title; + this.content = content; + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/review/exception/ReviewNotFoundException.java b/hackathon/src/main/java/com/techeer/hackathon/domain/review/exception/ReviewNotFoundException.java new file mode 100644 index 00000000..3c8bfdbd --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/review/exception/ReviewNotFoundException.java @@ -0,0 +1,10 @@ +package com.techeer.hackathon.domain.review.exception; + +import com.techeer.hackathon.global.error.ErrorCode; +import com.techeer.hackathon.global.error.exceptions.BusinessException; + +public class ReviewNotFoundException extends BusinessException { + public ReviewNotFoundException() { + super(ErrorCode.REVIEW_NOT_FOUND); + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/review/mapper/ReviewMapper.java b/hackathon/src/main/java/com/techeer/hackathon/domain/review/mapper/ReviewMapper.java new file mode 100644 index 00000000..2d67144b --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/review/mapper/ReviewMapper.java @@ -0,0 +1,44 @@ +package com.techeer.hackathon.domain.review.mapper; + +import com.techeer.hackathon.domain.restaurant.entity.Restaurant; +import com.techeer.hackathon.domain.review.dto.ReviewCreate; +import com.techeer.hackathon.domain.review.dto.ReviewInfo; +import com.techeer.hackathon.domain.review.dto.ReviewUpdateRequest; +import com.techeer.hackathon.domain.review.entity.Review; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.stream.Collectors; + +@Component +public class ReviewMapper { + public Review toEntity(ReviewCreate request, Restaurant restaurant) { + return Review.builder() + .restaurant(restaurant) + .content(request.getContent()) + .title(request.getTitle()) + .build(); + } + + public Review toEntity(ReviewUpdateRequest request, Restaurant restaurant) { + return Review.builder() + .restaurant(restaurant) + .content(request.getContent()) + .title(request.getTitle()) + .build(); + } + + + + public ReviewInfo toDto(Review review) { + return ReviewInfo.builder() + .restaurantName(review.getRestaurant().getName()) + .content(review.getContent()) + .title(review.getTitle()) + .build(); + } + + public List toDtoList(List list) { + return list.stream().map(this::toDto).collect(Collectors.toList()); + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/review/repository/ReviewRepository.java b/hackathon/src/main/java/com/techeer/hackathon/domain/review/repository/ReviewRepository.java new file mode 100644 index 00000000..199a4b86 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/review/repository/ReviewRepository.java @@ -0,0 +1,20 @@ +package com.techeer.hackathon.domain.review.repository; + +import com.techeer.hackathon.domain.review.entity.Review; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.transaction.annotation.Transactional; + +public interface ReviewRepository extends JpaRepository { + + @Modifying + @Transactional + @Query("update Review r set r.content = '' where r.id = :id") + void softDeleteById(Long id); + +// @Modifying +// @Transactional +// @Query("update Review r set r.content = '' where r.id = :id") +// void update(Review review); +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/domain/review/service/ReviewService.java b/hackathon/src/main/java/com/techeer/hackathon/domain/review/service/ReviewService.java new file mode 100644 index 00000000..9c6fe32c --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/domain/review/service/ReviewService.java @@ -0,0 +1,52 @@ +package com.techeer.hackathon.domain.review.service; + +import com.techeer.hackathon.domain.restaurant.entity.Restaurant; +import com.techeer.hackathon.domain.restaurant.error.RestaurantNotFoundException; +import com.techeer.hackathon.domain.restaurant.repository.RestaurantRepository; +import com.techeer.hackathon.domain.review.dto.ReviewCreate; +import com.techeer.hackathon.domain.review.dto.ReviewInfo; +import com.techeer.hackathon.domain.review.dto.ReviewUpdateRequest; +import com.techeer.hackathon.domain.review.entity.Review; +import com.techeer.hackathon.domain.review.exception.ReviewNotFoundException; +import com.techeer.hackathon.domain.review.mapper.ReviewMapper; +import com.techeer.hackathon.domain.review.repository.ReviewRepository; +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public class ReviewService { + private final ReviewRepository reviewRepository; + private final RestaurantRepository restaurantRepository; + private final ReviewMapper reviewMapper; + + public void createReview(ReviewCreate request) { + Restaurant restaurant = restaurantRepository.findByName(request.getRestaurantName()).orElseThrow(RestaurantNotFoundException::new); + reviewRepository.save(reviewMapper.toEntity(request, restaurant)); + } + + public ReviewInfo getReview(Long id) { + Review review = reviewRepository.findById(id).orElseThrow(ReviewNotFoundException::new); + return reviewMapper.toDto(review); + } + + public void deleteReview(Long id) { + reviewRepository.findById(id).orElseThrow(ReviewNotFoundException::new); + reviewRepository.deleteById(id); + } + + public void updateReview(ReviewUpdateRequest reviewUpdateRequest) { + Review findReview = reviewRepository.findById(reviewUpdateRequest.getId()).orElseThrow(ReviewNotFoundException::new); + Review review = reviewMapper.toEntity(reviewUpdateRequest, findReview.getRestaurant()); + reviewRepository.save(review); + } + + public List getReviews(PageRequest pageRequest) { + List reviews = reviewRepository.findAll(pageRequest).getContent(); + return reviewMapper.toDtoList(reviews); + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/global/config/JpaAuditingConfig.java b/hackathon/src/main/java/com/techeer/hackathon/global/config/JpaAuditingConfig.java new file mode 100644 index 00000000..5114d22f --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/global/config/JpaAuditingConfig.java @@ -0,0 +1,8 @@ +package com.techeer.hackathon.global.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@Configuration +@EnableJpaAuditing +public class JpaAuditingConfig {} diff --git a/hackathon/src/main/java/com/techeer/hackathon/global/config/SwaggerConfig.java b/hackathon/src/main/java/com/techeer/hackathon/global/config/SwaggerConfig.java new file mode 100644 index 00000000..3c18e761 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/global/config/SwaggerConfig.java @@ -0,0 +1,49 @@ +package com.techeer.hackathon.global.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + +import java.util.HashSet; +import java.util.Set; + +@Configuration +@EnableWebMvc +public class SwaggerConfig { + + private ApiInfo swaggerInfo() { + return new ApiInfoBuilder().title("Hackathon API").description("Hackathon API Docs").build(); + } + + @Bean + public Docket swaggerApi() { + return new Docket(DocumentationType.SWAGGER_2) + .consumes(getConsumeContentTypes()) + .produces(getProduceContentTypes()) + .apiInfo(swaggerInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("com.techeer.hackathon")) + .paths(PathSelectors.any()) + .build() + .useDefaultResponseMessages(false); + } + + private Set getConsumeContentTypes() { + Set consumes = new HashSet<>(); + consumes.add("application/json;charset=UTF-8"); + consumes.add("application/x-www-form-urlencoded"); + return consumes; + } + + private Set getProduceContentTypes() { + Set produces = new HashSet<>(); + produces.add("application/json;charset=UTF-8"); + return produces; + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/global/error/ErrorCode.java b/hackathon/src/main/java/com/techeer/hackathon/global/error/ErrorCode.java new file mode 100644 index 00000000..59723e99 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/global/error/ErrorCode.java @@ -0,0 +1,24 @@ +package com.techeer.hackathon.global.error; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum ErrorCode { + // Global + INTERNAL_SERVER_ERROR(500, "G001", "서버 오류"), + INPUT_INVALID_VALUE(409, "G002", "잘못된 입력"), + + // Restaurant + RESTAURANT_DUPLICATION_ERROR(409, "R001", "레스토랑 이름이 중복됩니다."), + INVALID_CATEGORY_ERROR(400, "R002", "잘못된 카테고리 이름입니다."), + RESTAURANT_NOT_FOUND(404, "R003", "식당을 찾을 수 없습니다."), + + REVIEW_NOT_FOUND(404, "V001", "리뷰를 찾을 수 없습니다."); + + private final int status; + private final String code; + private final String message; +} + diff --git a/hackathon/src/main/java/com/techeer/hackathon/global/error/ErrorResponse.java b/hackathon/src/main/java/com/techeer/hackathon/global/error/ErrorResponse.java new file mode 100644 index 00000000..4ac725da --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/global/error/ErrorResponse.java @@ -0,0 +1,62 @@ +package com.techeer.hackathon.global.error; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import org.springframework.validation.BindingResult; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@Builder +@Getter +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class ErrorResponse { + private String businessCode; + private String errorMessage; + private List errors; + + private ErrorResponse(ErrorCode code, List fieldErrors) { + this.businessCode = code.getCode(); + this.errorMessage = code.getMessage(); + this.errors = fieldErrors; + } + + private ErrorResponse(ErrorCode code) { + this.businessCode = code.getCode(); + this.errorMessage = code.getMessage(); + this.errors = new ArrayList<>(); + } + + public static ErrorResponse of(final ErrorCode code, final BindingResult bindingResult) { + return new ErrorResponse(code, FieldError.of(bindingResult)); + } + + public static ErrorResponse of(ErrorCode code) { + return new ErrorResponse(code); + } + + @Getter + @AllArgsConstructor + public static class FieldError { + private String field; + private String value; + private String reason; + + private static List of(final BindingResult bindingResult) { + final List fieldErrors = + bindingResult.getFieldErrors(); + return fieldErrors.stream() + .map( + error -> + new FieldError( + error.getField(), + error.getRejectedValue() == null ? "" : error.getRejectedValue().toString(), + error.getDefaultMessage())) + .collect(Collectors.toList()); + } + } +} + diff --git a/hackathon/src/main/java/com/techeer/hackathon/global/error/GlobalExceptionHandler.java b/hackathon/src/main/java/com/techeer/hackathon/global/error/GlobalExceptionHandler.java new file mode 100644 index 00000000..b4fd57af --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/global/error/GlobalExceptionHandler.java @@ -0,0 +1,43 @@ +package com.techeer.hackathon.global.error; + +import com.techeer.hackathon.global.error.exceptions.BusinessException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import static com.techeer.hackathon.global.error.ErrorCode.INPUT_INVALID_VALUE; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(Exception.class) + protected ResponseEntity handleException(Exception e) { + log.error(e.getMessage(), e); + ErrorResponse response = ErrorResponse.of(ErrorCode.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler + protected ResponseEntity handleRuntimeException(BusinessException e) { + final ErrorCode errorCode = e.getErrorCode(); + final ErrorResponse response = + ErrorResponse.builder() + .errorMessage(errorCode.getMessage()) + .businessCode(errorCode.getCode()) + .build(); + log.warn(e.getMessage()); + return ResponseEntity.status(errorCode.getStatus()).body(response); + } + + @ExceptionHandler + protected ResponseEntity handleMethodArgumentNotValidException( + MethodArgumentNotValidException e) { + final ErrorResponse response = ErrorResponse.of(INPUT_INVALID_VALUE, e.getBindingResult()); + log.warn(e.getMessage()); + return ResponseEntity.status(INPUT_INVALID_VALUE.getStatus()).body(response); + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/global/error/exceptions/BusinessException.java b/hackathon/src/main/java/com/techeer/hackathon/global/error/exceptions/BusinessException.java new file mode 100644 index 00000000..d77f08ba --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/global/error/exceptions/BusinessException.java @@ -0,0 +1,14 @@ +package com.techeer.hackathon.global.error.exceptions; + +import com.techeer.hackathon.global.error.ErrorCode; +import lombok.Getter; + +@Getter +public class BusinessException extends RuntimeException { + private final ErrorCode errorCode; + + public BusinessException(ErrorCode errorCode) { + super(errorCode.getMessage()); + this.errorCode = errorCode; + } +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/global/result/ResultCode.java b/hackathon/src/main/java/com/techeer/hackathon/global/result/ResultCode.java new file mode 100644 index 00000000..c7cc1295 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/global/result/ResultCode.java @@ -0,0 +1,24 @@ +package com.techeer.hackathon.global.result; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum ResultCode { + + RESTAURANT_CREATE_SUCCESS("R001", "레스토랑 생성 성공"), + CHANGE_CATEGORY_SUCCESS("R002", "카테고리 변경 성공"), + GET_ALL_RESTAURANTS_SUCCESS("R003", "전체 카테고리 조회 성공"), + DELETE_RESTAURANTS_SUCCESS("R004", "레스토랑 삭제 성공"), + GET_RESTAURANTS_SUCCESS("R005", "카테고리 조회 성공"), + + REVIEW_CREATE_SUCCESS("V001", "리뷰 등록 성공"), + GET_REVIEW_SUCCESS("V002", "리뷰 조회 성공"), + DELETE_REVIEW_SUCCESS("V003", "리뷰 삭제 성공"), + UPDATE_REVIEW_SUCCESS("V004", "리뷰 수정 성공"), + GET_ALL_REVIEW_SUCCESS("V005", "리뷰 페이징 조회 성공"); + + private final String code; + private final String message; +} diff --git a/hackathon/src/main/java/com/techeer/hackathon/global/result/ResultResponse.java b/hackathon/src/main/java/com/techeer/hackathon/global/result/ResultResponse.java new file mode 100644 index 00000000..254dd1f2 --- /dev/null +++ b/hackathon/src/main/java/com/techeer/hackathon/global/result/ResultResponse.java @@ -0,0 +1,25 @@ +package com.techeer.hackathon.global.result; + +import lombok.Getter; + +@Getter +public class ResultResponse { + + private String code; + private String message; + private Object data; + + public static ResultResponse of(ResultCode resultCode, Object data) { + return new ResultResponse(resultCode, data); + } + + public static ResultResponse of(ResultCode resultCode) { + return new ResultResponse(resultCode, ""); + } + + public ResultResponse(ResultCode resultCode, Object data) { + this.code = resultCode.getCode(); + this.message = resultCode.getMessage(); + this.data = data; + } +} diff --git a/hackathon/src/main/resources/application.yml b/hackathon/src/main/resources/application.yml new file mode 100644 index 00000000..f1f0d7b3 --- /dev/null +++ b/hackathon/src/main/resources/application.yml @@ -0,0 +1,18 @@ +spring: + application: + name: hackathon + jpa: + database: "mysql" + show-sql: "true" + hibernate: + ddl-auto: "update" + properties: + hibernate: + format_sql: true + generate-ddl: true + + datasource: + driver-class-name: "com.mysql.cj.jdbc.Driver" + url: "jdbc:mysql://localhost:3306/hackathon" + username: "root" + password: "0000" \ No newline at end of file diff --git a/hackathon/src/test/java/com/techeer/hackathon/HackathonApplicationTests.java b/hackathon/src/test/java/com/techeer/hackathon/HackathonApplicationTests.java new file mode 100644 index 00000000..9cabab03 --- /dev/null +++ b/hackathon/src/test/java/com/techeer/hackathon/HackathonApplicationTests.java @@ -0,0 +1,13 @@ +package com.techeer.hackathon; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class HackathonApplicationTests { + + @Test + void contextLoads() { + } + +}