diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..d406152fe --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +HELP.md +.gradle +build/* +!build/generated-snippets +!build/generated-snippets/* +!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/ \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..d2e7bed1a --- /dev/null +++ b/build.gradle @@ -0,0 +1,51 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.5' + id 'io.spring.dependency-management' version '1.1.3' + id 'org.asciidoctor.jvm.convert' version '3.3.2' +} + +group = 'com.programmers' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +ext { + set('snippetsDir', file("build/generated-snippets")) +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.h2database:h2' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' +} + +tasks.named('bootBuildImage') { + builder = 'paketobuildpacks/builder-jammy-base:latest' +} + +tasks.named('test') { + outputs.dir snippetsDir + useJUnitPlatform() +} + +tasks.named('asciidoctor') { + inputs.dir snippetsDir + dependsOn test +} diff --git a/build/generated-snippets/post-create/curl-request.adoc b/build/generated-snippets/post-create/curl-request.adoc new file mode 100644 index 000000000..66001d946 --- /dev/null +++ b/build/generated-snippets/post-create/curl-request.adoc @@ -0,0 +1,6 @@ +[source,bash] +---- +$ curl 'http://localhost:8080/posts' -i -X POST \ + -H 'Content-Type: application/json;charset=UTF-8' \ + -d '{"title":"title","content":"content","userId":4}' +---- \ No newline at end of file diff --git a/build/generated-snippets/post-create/http-request.adoc b/build/generated-snippets/post-create/http-request.adoc new file mode 100644 index 000000000..9a3f1613c --- /dev/null +++ b/build/generated-snippets/post-create/http-request.adoc @@ -0,0 +1,9 @@ +[source,http,options="nowrap"] +---- +POST /posts HTTP/1.1 +Content-Type: application/json;charset=UTF-8 +Content-Length: 48 +Host: localhost:8080 + +{"title":"title","content":"content","userId":4} +---- \ No newline at end of file diff --git a/build/generated-snippets/post-create/http-response.adoc b/build/generated-snippets/post-create/http-response.adoc new file mode 100644 index 000000000..65a7ffcec --- /dev/null +++ b/build/generated-snippets/post-create/http-response.adoc @@ -0,0 +1,8 @@ +[source,http,options="nowrap"] +---- +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 212 + +{"code":0,"data":{"postId":4,"title":"title","content":"content","user":{"userId":4,"name":"username","age":26,"hobby":"testHobby"},"createdAt":"2023-11-18T21:25:14.113386","createdBy":"username"},"success":true} +---- \ No newline at end of file diff --git a/build/generated-snippets/post-create/httpie-request.adoc b/build/generated-snippets/post-create/httpie-request.adoc new file mode 100644 index 000000000..3f5c33e94 --- /dev/null +++ b/build/generated-snippets/post-create/httpie-request.adoc @@ -0,0 +1,5 @@ +[source,bash] +---- +$ echo '{"title":"title","content":"content","userId":4}' | http POST 'http://localhost:8080/posts' \ + 'Content-Type:application/json;charset=UTF-8' +---- \ No newline at end of file diff --git a/build/generated-snippets/post-create/request-body.adoc b/build/generated-snippets/post-create/request-body.adoc new file mode 100644 index 000000000..6af39e9a3 --- /dev/null +++ b/build/generated-snippets/post-create/request-body.adoc @@ -0,0 +1,4 @@ +[source,json,options="nowrap"] +---- +{"title":"title","content":"content","userId":4} +---- \ No newline at end of file diff --git a/build/generated-snippets/post-create/request-fields.adoc b/build/generated-snippets/post-create/request-fields.adoc new file mode 100644 index 000000000..2e2af2dc6 --- /dev/null +++ b/build/generated-snippets/post-create/request-fields.adoc @@ -0,0 +1,16 @@ +|=== +|Path|Type|Description + +|`+title+` +|`+String+` +|제목 + +|`+content+` +|`+String+` +|컨텐츠 + +|`+userId+` +|`+Number+` +|유저 ID + +|=== \ No newline at end of file diff --git a/build/generated-snippets/post-create/response-body.adoc b/build/generated-snippets/post-create/response-body.adoc new file mode 100644 index 000000000..c257f14b4 --- /dev/null +++ b/build/generated-snippets/post-create/response-body.adoc @@ -0,0 +1,4 @@ +[source,json,options="nowrap"] +---- +{"code":0,"data":{"postId":4,"title":"title","content":"content","user":{"userId":4,"name":"username","age":26,"hobby":"testHobby"},"createdAt":"2023-11-18T21:25:14.113386","createdBy":"username"},"success":true} +---- \ No newline at end of file diff --git a/build/generated-snippets/post-create/response-fields.adoc b/build/generated-snippets/post-create/response-fields.adoc new file mode 100644 index 000000000..15ec49226 --- /dev/null +++ b/build/generated-snippets/post-create/response-fields.adoc @@ -0,0 +1,48 @@ +|=== +|Path|Type|Description + +|`+code+` +|`+Number+` +|응답 코드 + +|`+data.postId+` +|`+Number+` +|포스트 ID + +|`+data.title+` +|`+String+` +|제목 + +|`+data.content+` +|`+String+` +|컨텐츠 + +|`+data.user.userId+` +|`+Number+` +|유저 ID + +|`+data.user.name+` +|`+String+` +|유저 이름 + +|`+data.user.age+` +|`+Number+` +|유저 나이 + +|`+data.user.hobby+` +|`+String+` +|유저 취미 + +|`+data.createdAt+` +|`+String+` +|작성 시간 + +|`+data.createdBy+` +|`+String+` +|작성자 + +|`+success+` +|`+Boolean+` +|성공 여부 + +|=== \ No newline at end of file diff --git a/build/generated-snippets/post-getAllPost/curl-request.adoc b/build/generated-snippets/post-getAllPost/curl-request.adoc new file mode 100644 index 000000000..ab5425b26 --- /dev/null +++ b/build/generated-snippets/post-getAllPost/curl-request.adoc @@ -0,0 +1,4 @@ +[source,bash] +---- +$ curl 'http://localhost:8080/posts?page=0&size=10' -i -X GET +---- \ No newline at end of file diff --git a/build/generated-snippets/post-getAllPost/http-request.adoc b/build/generated-snippets/post-getAllPost/http-request.adoc new file mode 100644 index 000000000..65aaa0993 --- /dev/null +++ b/build/generated-snippets/post-getAllPost/http-request.adoc @@ -0,0 +1,6 @@ +[source,http,options="nowrap"] +---- +GET /posts?page=0&size=10 HTTP/1.1 +Host: localhost:8080 + +---- \ No newline at end of file diff --git a/build/generated-snippets/post-getAllPost/http-response.adoc b/build/generated-snippets/post-getAllPost/http-response.adoc new file mode 100644 index 000000000..acbb91835 --- /dev/null +++ b/build/generated-snippets/post-getAllPost/http-response.adoc @@ -0,0 +1,8 @@ +[source,http,options="nowrap"] +---- +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 531 + +{"code":0,"data":{"content":[{"postId":3,"title":"제목","content":"컨텐츠","user":{"userId":3,"name":"username","age":26,"hobby":"testHobby"},"createdAt":"2023-11-18T21:25:14.072675","createdBy":"username"}],"pageable":{"pageNumber":0,"pageSize":10,"sort":{"empty":true,"sorted":false,"unsorted":true},"offset":0,"paged":true,"unpaged":false},"last":true,"totalElements":1,"totalPages":1,"first":true,"size":10,"number":0,"sort":{"empty":true,"sorted":false,"unsorted":true},"numberOfElements":1,"empty":false},"success":true} +---- \ No newline at end of file diff --git a/build/generated-snippets/post-getAllPost/httpie-request.adoc b/build/generated-snippets/post-getAllPost/httpie-request.adoc new file mode 100644 index 000000000..3a36ed03a --- /dev/null +++ b/build/generated-snippets/post-getAllPost/httpie-request.adoc @@ -0,0 +1,4 @@ +[source,bash] +---- +$ http GET 'http://localhost:8080/posts?page=0&size=10' +---- \ No newline at end of file diff --git a/build/generated-snippets/post-getAllPost/request-body.adoc b/build/generated-snippets/post-getAllPost/request-body.adoc new file mode 100644 index 000000000..dab5f81d2 --- /dev/null +++ b/build/generated-snippets/post-getAllPost/request-body.adoc @@ -0,0 +1,4 @@ +[source,options="nowrap"] +---- + +---- \ No newline at end of file diff --git a/build/generated-snippets/post-getAllPost/response-body.adoc b/build/generated-snippets/post-getAllPost/response-body.adoc new file mode 100644 index 000000000..9e069b8dc --- /dev/null +++ b/build/generated-snippets/post-getAllPost/response-body.adoc @@ -0,0 +1,4 @@ +[source,json,options="nowrap"] +---- +{"code":0,"data":{"content":[{"postId":3,"title":"제목","content":"컨텐츠","user":{"userId":3,"name":"username","age":26,"hobby":"testHobby"},"createdAt":"2023-11-18T21:25:14.072675","createdBy":"username"}],"pageable":{"pageNumber":0,"pageSize":10,"sort":{"empty":true,"sorted":false,"unsorted":true},"offset":0,"paged":true,"unpaged":false},"last":true,"totalElements":1,"totalPages":1,"first":true,"size":10,"number":0,"sort":{"empty":true,"sorted":false,"unsorted":true},"numberOfElements":1,"empty":false},"success":true} +---- \ No newline at end of file diff --git a/build/generated-snippets/post-getAllPost/response-fields.adoc b/build/generated-snippets/post-getAllPost/response-fields.adoc new file mode 100644 index 000000000..1a24bf66a --- /dev/null +++ b/build/generated-snippets/post-getAllPost/response-fields.adoc @@ -0,0 +1,124 @@ +|=== +|Path|Type|Description + +|`+code+` +|`+Number+` +|응답 코드 + +|`+data.content[].postId+` +|`+Number+` +|포스트 ID + +|`+data.content[].title+` +|`+String+` +|제목 + +|`+data.content[].content+` +|`+String+` +|컨텐츠 + +|`+data.content[].user.userId+` +|`+Number+` +|유저 ID + +|`+data.content[].user.name+` +|`+String+` +|유저 이름 + +|`+data.content[].user.age+` +|`+Number+` +|유저 나이 + +|`+data.content[].user.hobby+` +|`+String+` +|유저 취미 + +|`+data.content[].createdAt+` +|`+String+` +|작성 시간 + +|`+data.content[].createdBy+` +|`+String+` +|작성자 + +|`+data.pageable.pageNumber+` +|`+Number+` +|페이지 번호 + +|`+data.pageable.pageSize+` +|`+Number+` +|페이지 크기 + +|`+data.pageable.sort.empty+` +|`+Boolean+` +|공백 여부 + +|`+data.pageable.sort.sorted+` +|`+Boolean+` +|정렬 여부(O) + +|`+data.pageable.sort.unsorted+` +|`+Boolean+` +|정렬 여부 (X) + +|`+data.pageable.offset+` +|`+Number+` +|오프셋 + +|`+data.pageable.paged+` +|`+Boolean+` +|페이지 여부(O) + +|`+data.pageable.unpaged+` +|`+Boolean+` +|페이지 여부(X) + +|`+data.last+` +|`+Boolean+` +|마지막 여부 + +|`+data.totalPages+` +|`+Number+` +|전체 페이지 + +|`+data.totalElements+` +|`+Number+` +|전체 원소 개수 + +|`+data.first+` +|`+Boolean+` +|처음 여부 + +|`+data.size+` +|`+Number+` +|크기 + +|`+data.number+` +|`+Number+` +|번호 + +|`+data.sort.empty+` +|`+Boolean+` +|정렬 공백 여부 + +|`+data.sort.sorted+` +|`+Boolean+` +|정렬 여부(O) + +|`+data.sort.unsorted+` +|`+Boolean+` +|정렬 여부(X) + +|`+data.numberOfElements+` +|`+Number+` +|원소 갯수 + +|`+data.empty+` +|`+Boolean+` +|공백 여부 + +|`+success+` +|`+Boolean+` +|성공 여부 + +|=== \ No newline at end of file diff --git a/build/generated-snippets/post-getById/curl-request.adoc b/build/generated-snippets/post-getById/curl-request.adoc new file mode 100644 index 000000000..e9d36dbc3 --- /dev/null +++ b/build/generated-snippets/post-getById/curl-request.adoc @@ -0,0 +1,4 @@ +[source,bash] +---- +$ curl 'http://localhost:8080/posts/1' -i -X GET +---- \ No newline at end of file diff --git a/build/generated-snippets/post-getById/http-request.adoc b/build/generated-snippets/post-getById/http-request.adoc new file mode 100644 index 000000000..c92153664 --- /dev/null +++ b/build/generated-snippets/post-getById/http-request.adoc @@ -0,0 +1,6 @@ +[source,http,options="nowrap"] +---- +GET /posts/1 HTTP/1.1 +Host: localhost:8080 + +---- \ No newline at end of file diff --git a/build/generated-snippets/post-getById/http-response.adoc b/build/generated-snippets/post-getById/http-response.adoc new file mode 100644 index 000000000..0bb786d99 --- /dev/null +++ b/build/generated-snippets/post-getById/http-response.adoc @@ -0,0 +1,8 @@ +[source,http,options="nowrap"] +---- +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 215 + +{"code":0,"data":{"postId":1,"title":"제목","content":"컨텐츠","user":{"userId":1,"name":"username","age":26,"hobby":"testHobby"},"createdAt":"2023-11-18T21:25:13.912605","createdBy":"username"},"success":true} +---- \ No newline at end of file diff --git a/build/generated-snippets/post-getById/httpie-request.adoc b/build/generated-snippets/post-getById/httpie-request.adoc new file mode 100644 index 000000000..e5a490910 --- /dev/null +++ b/build/generated-snippets/post-getById/httpie-request.adoc @@ -0,0 +1,4 @@ +[source,bash] +---- +$ http GET 'http://localhost:8080/posts/1' +---- \ No newline at end of file diff --git a/build/generated-snippets/post-getById/request-body.adoc b/build/generated-snippets/post-getById/request-body.adoc new file mode 100644 index 000000000..dab5f81d2 --- /dev/null +++ b/build/generated-snippets/post-getById/request-body.adoc @@ -0,0 +1,4 @@ +[source,options="nowrap"] +---- + +---- \ No newline at end of file diff --git a/build/generated-snippets/post-getById/response-body.adoc b/build/generated-snippets/post-getById/response-body.adoc new file mode 100644 index 000000000..f172b9dcb --- /dev/null +++ b/build/generated-snippets/post-getById/response-body.adoc @@ -0,0 +1,4 @@ +[source,json,options="nowrap"] +---- +{"code":0,"data":{"postId":1,"title":"제목","content":"컨텐츠","user":{"userId":1,"name":"username","age":26,"hobby":"testHobby"},"createdAt":"2023-11-18T21:25:13.912605","createdBy":"username"},"success":true} +---- \ No newline at end of file diff --git a/build/generated-snippets/post-getById/response-fields.adoc b/build/generated-snippets/post-getById/response-fields.adoc new file mode 100644 index 000000000..15ec49226 --- /dev/null +++ b/build/generated-snippets/post-getById/response-fields.adoc @@ -0,0 +1,48 @@ +|=== +|Path|Type|Description + +|`+code+` +|`+Number+` +|응답 코드 + +|`+data.postId+` +|`+Number+` +|포스트 ID + +|`+data.title+` +|`+String+` +|제목 + +|`+data.content+` +|`+String+` +|컨텐츠 + +|`+data.user.userId+` +|`+Number+` +|유저 ID + +|`+data.user.name+` +|`+String+` +|유저 이름 + +|`+data.user.age+` +|`+Number+` +|유저 나이 + +|`+data.user.hobby+` +|`+String+` +|유저 취미 + +|`+data.createdAt+` +|`+String+` +|작성 시간 + +|`+data.createdBy+` +|`+String+` +|작성자 + +|`+success+` +|`+Boolean+` +|성공 여부 + +|=== \ No newline at end of file diff --git a/build/generated-snippets/post-update/curl-request.adoc b/build/generated-snippets/post-update/curl-request.adoc new file mode 100644 index 000000000..e904379aa --- /dev/null +++ b/build/generated-snippets/post-update/curl-request.adoc @@ -0,0 +1,6 @@ +[source,bash] +---- +$ curl 'http://localhost:8080/posts/2' -i -X POST \ + -H 'Content-Type: application/json;charset=UTF-8' \ + -d '{"title":"title","content":"content"}' +---- \ No newline at end of file diff --git a/build/generated-snippets/post-update/http-request.adoc b/build/generated-snippets/post-update/http-request.adoc new file mode 100644 index 000000000..6dcf75277 --- /dev/null +++ b/build/generated-snippets/post-update/http-request.adoc @@ -0,0 +1,9 @@ +[source,http,options="nowrap"] +---- +POST /posts/2 HTTP/1.1 +Content-Type: application/json;charset=UTF-8 +Content-Length: 37 +Host: localhost:8080 + +{"title":"title","content":"content"} +---- \ No newline at end of file diff --git a/build/generated-snippets/post-update/http-response.adoc b/build/generated-snippets/post-update/http-response.adoc new file mode 100644 index 000000000..1a733f13a --- /dev/null +++ b/build/generated-snippets/post-update/http-response.adoc @@ -0,0 +1,8 @@ +[source,http,options="nowrap"] +---- +HTTP/1.1 200 OK +Content-Type: application/json +Content-Length: 41 + +{"code":0,"data":"성공","success":true} +---- \ No newline at end of file diff --git a/build/generated-snippets/post-update/httpie-request.adoc b/build/generated-snippets/post-update/httpie-request.adoc new file mode 100644 index 000000000..f4e9fc472 --- /dev/null +++ b/build/generated-snippets/post-update/httpie-request.adoc @@ -0,0 +1,5 @@ +[source,bash] +---- +$ echo '{"title":"title","content":"content"}' | http POST 'http://localhost:8080/posts/2' \ + 'Content-Type:application/json;charset=UTF-8' +---- \ No newline at end of file diff --git a/build/generated-snippets/post-update/request-body.adoc b/build/generated-snippets/post-update/request-body.adoc new file mode 100644 index 000000000..2820aecc3 --- /dev/null +++ b/build/generated-snippets/post-update/request-body.adoc @@ -0,0 +1,4 @@ +[source,json,options="nowrap"] +---- +{"title":"title","content":"content"} +---- \ No newline at end of file diff --git a/build/generated-snippets/post-update/request-fields.adoc b/build/generated-snippets/post-update/request-fields.adoc new file mode 100644 index 000000000..9b741d453 --- /dev/null +++ b/build/generated-snippets/post-update/request-fields.adoc @@ -0,0 +1,12 @@ +|=== +|Path|Type|Description + +|`+title+` +|`+String+` +|제목 + +|`+content+` +|`+String+` +|컨텐츠 + +|=== \ No newline at end of file diff --git a/build/generated-snippets/post-update/response-body.adoc b/build/generated-snippets/post-update/response-body.adoc new file mode 100644 index 000000000..7eddf878e --- /dev/null +++ b/build/generated-snippets/post-update/response-body.adoc @@ -0,0 +1,4 @@ +[source,json,options="nowrap"] +---- +{"code":0,"data":"성공","success":true} +---- \ No newline at end of file diff --git a/build/generated-snippets/post-update/response-fields.adoc b/build/generated-snippets/post-update/response-fields.adoc new file mode 100644 index 000000000..c331da500 --- /dev/null +++ b/build/generated-snippets/post-update/response-fields.adoc @@ -0,0 +1,16 @@ +|=== +|Path|Type|Description + +|`+code+` +|`+Number+` +|응답 코드 + +|`+data+` +|`+String+` +|응답 메시지 + +|`+success+` +|`+Boolean+` +|성공 여부 + +|=== \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..7f93135c4 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..3fa8f862f --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 000000000..1aa94a426 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..0795530c5 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'springboot-board-jpa' diff --git a/src/docs/asciidoc/index.adoc b/src/docs/asciidoc/index.adoc new file mode 100644 index 000000000..1879061a3 --- /dev/null +++ b/src/docs/asciidoc/index.adoc @@ -0,0 +1,50 @@ +:hardbreaks: +ifndef::snippets[] +:snippets: ../../../build/generated-snippets +endif::[] + +== 포스트 + +=== 포스트 생성 + +==== /post +.Request +include::{snippets}/post-create/http-request.adoc[] +.Request Fields +include::{snippets}/post-create/request-fields.adoc[] +.Response +include::{snippets}/post-create/http-response.adoc[] +.Response Fields +include::{snippets}/post-create/response-fields.adoc[] + +=== 포스트 업데이트 + +==== /post/{id} +.Request +include::{snippets}/post-update/http-request.adoc[] +.Request Fields +include::{snippets}/post-update/request-fields.adoc[] +.Response +include::{snippets}/post-update/http-response.adoc[] +.Response Fields +include::{snippets}/post-update/response-fields.adoc[] + +=== 포스트 조회 (id 기반 단건) + +==== /post/{id} +.Request +include::{snippets}/post-getById/http-request.adoc[] +.Response +include::{snippets}/post-getById/http-response.adoc[] +.Response Fields +include::{snippets}/post-getById/response-fields.adoc[] + +=== 포스트 전체 조회 + +==== /post +.Request +include::{snippets}/post-getAllPost/http-request.adoc[] +.Response +include::{snippets}/post-getAllPost/http-response.adoc[] +.Response Fields +include::{snippets}/post-getAllPost/response-fields.adoc[] \ No newline at end of file diff --git a/src/main/java/com/programmers/springbootboardjpa/SpringbootBoardJpaApplication.java b/src/main/java/com/programmers/springbootboardjpa/SpringbootBoardJpaApplication.java new file mode 100644 index 000000000..29376e6b7 --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/SpringbootBoardJpaApplication.java @@ -0,0 +1,13 @@ +package com.programmers.springbootboardjpa; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootBoardJpaApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootBoardJpaApplication.class, args); + } + +} diff --git a/src/main/java/com/programmers/springbootboardjpa/controller/PostRestController.java b/src/main/java/com/programmers/springbootboardjpa/controller/PostRestController.java new file mode 100644 index 000000000..53d93723c --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/controller/PostRestController.java @@ -0,0 +1,63 @@ +package com.programmers.springbootboardjpa.controller; + +import com.programmers.springbootboardjpa.dto.PostControllerCreateRequestDto; +import com.programmers.springbootboardjpa.dto.PostControllerUpdateRequestDto; +import com.programmers.springbootboardjpa.dto.PostServiceRequestDto; +import com.programmers.springbootboardjpa.dto.PostServiceResponseDto; +import com.programmers.springbootboardjpa.exception.ErrorMsg; +import com.programmers.springbootboardjpa.exception.PostNotFoundException; +import com.programmers.springbootboardjpa.exception.UserNotFoundException; +import com.programmers.springbootboardjpa.model.CommonResult; +import com.programmers.springbootboardjpa.service.PostService; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/posts") +public class PostRestController { + private final PostService postService; + + @ExceptionHandler(UserNotFoundException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + protected CommonResult userNotFoundException(UserNotFoundException e) { + return CommonResult.getFailResult(ErrorMsg.USER_NOT_FOUND.getCode(), e.getMessage()); + } + + @ExceptionHandler(PostNotFoundException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + protected CommonResult postNotFoundException(PostNotFoundException e) { + return CommonResult.getFailResult(ErrorMsg.POST_NOT_FOUND.getCode(), e.getMessage()); + } + + @GetMapping + public CommonResult> getAllPost(Pageable pageable) { + return CommonResult.getResult(postService.findAll(pageable)); + } + + @GetMapping("/{id}") + public CommonResult getPostById(@PathVariable Long id) { + return CommonResult.getResult(postService.findPostById(id)); + } + + @PostMapping + public CommonResult createPost(@RequestBody PostControllerCreateRequestDto requestDto) { + return CommonResult.getResult(postService.create(PostServiceRequestDto.builder() + .title(requestDto.getTitle()) + .content(requestDto.getContent()) + .userId(requestDto.getUserId()) + .build())); + } + + @PostMapping("/{id}") + public CommonResult updatePost(@PathVariable Long id, @RequestBody PostControllerUpdateRequestDto requestDto) { + postService.update(id, PostServiceRequestDto.builder() + .title(requestDto.getTitle()) + .content(requestDto.getContent()) + .build()); + return CommonResult.getSuccessResult(); + } +} diff --git a/src/main/java/com/programmers/springbootboardjpa/dto/PostControllerCreateRequestDto.java b/src/main/java/com/programmers/springbootboardjpa/dto/PostControllerCreateRequestDto.java new file mode 100644 index 000000000..a0829ba70 --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/dto/PostControllerCreateRequestDto.java @@ -0,0 +1,12 @@ +package com.programmers.springbootboardjpa.dto; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public class PostControllerCreateRequestDto { + private final String title; + private final String content; + private final Long userId; +} diff --git a/src/main/java/com/programmers/springbootboardjpa/dto/PostControllerUpdateRequestDto.java b/src/main/java/com/programmers/springbootboardjpa/dto/PostControllerUpdateRequestDto.java new file mode 100644 index 000000000..c179e07dd --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/dto/PostControllerUpdateRequestDto.java @@ -0,0 +1,11 @@ +package com.programmers.springbootboardjpa.dto; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public class PostControllerUpdateRequestDto { + private final String title; + private final String content; +} diff --git a/src/main/java/com/programmers/springbootboardjpa/dto/PostServiceRequestDto.java b/src/main/java/com/programmers/springbootboardjpa/dto/PostServiceRequestDto.java new file mode 100644 index 000000000..8e5dc3c69 --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/dto/PostServiceRequestDto.java @@ -0,0 +1,18 @@ +package com.programmers.springbootboardjpa.dto; + + +import lombok.*; + +@Getter +public class PostServiceRequestDto { + private final String title; + private final String content; + private final Long userId; + + @Builder + protected PostServiceRequestDto(String title, String content, Long userId) { + this.title = title; + this.content = content; + this.userId = userId; + } +} diff --git a/src/main/java/com/programmers/springbootboardjpa/dto/PostServiceResponseDto.java b/src/main/java/com/programmers/springbootboardjpa/dto/PostServiceResponseDto.java new file mode 100644 index 000000000..6e4b15f2e --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/dto/PostServiceResponseDto.java @@ -0,0 +1,34 @@ +package com.programmers.springbootboardjpa.dto; + +import com.programmers.springbootboardjpa.entity.Post; +import lombok.Getter; + +import java.time.LocalDateTime; + +@Getter +public class PostServiceResponseDto { + private final Long postId; + private final String title; + private final String content; + private final UserDto user; + private final LocalDateTime createdAt; + private final String createdBy; + + private PostServiceResponseDto(Long postId, String title, String content, UserDto user, LocalDateTime createdAt, String createdBy) { + this.postId = postId; + this.title = title; + this.content = content; + this.user = user; + this.createdAt = createdAt; + this.createdBy = createdBy; + } + + public static PostServiceResponseDto of(Post post) { + return new PostServiceResponseDto(post.getId(), + post.getTitle(), + post.getContent(), + UserDto.of(post.getUser()), + post.getCreatedAt(), + post.getCreatedBy()); + } +} diff --git a/src/main/java/com/programmers/springbootboardjpa/dto/UserDto.java b/src/main/java/com/programmers/springbootboardjpa/dto/UserDto.java new file mode 100644 index 000000000..f9f4a262d --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/dto/UserDto.java @@ -0,0 +1,26 @@ +package com.programmers.springbootboardjpa.dto; + +import com.programmers.springbootboardjpa.entity.User; +import lombok.Getter; + +@Getter +public class UserDto { + private final long userId; + private final String name; + private final int age; + private final String hobby; + + private UserDto(long userId, String name, int age, String hobby) { + this.userId = userId; + this.name = name; + this.age = age; + this.hobby = hobby; + } + + public static UserDto of(User user){ + return new UserDto(user.getUserId(), + user.getName(), + user.getAge(), + user.getHobby()); + } +} diff --git a/src/main/java/com/programmers/springbootboardjpa/entity/BaseEntity.java b/src/main/java/com/programmers/springbootboardjpa/entity/BaseEntity.java new file mode 100644 index 000000000..6e912350e --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/entity/BaseEntity.java @@ -0,0 +1,23 @@ +package com.programmers.springbootboardjpa.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.PrePersist; +import lombok.Getter; + +import java.time.LocalDateTime; + +@MappedSuperclass +@Getter +public abstract class BaseEntity { + @Column(nullable = false, columnDefinition = "TIMESTAMP") + private LocalDateTime createdAt; + + @Column(nullable = false) + protected String createdBy; + + @PrePersist + public void onPrePersist() { + this.createdAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/programmers/springbootboardjpa/entity/Post.java b/src/main/java/com/programmers/springbootboardjpa/entity/Post.java new file mode 100644 index 000000000..842e34e54 --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/entity/Post.java @@ -0,0 +1,67 @@ +package com.programmers.springbootboardjpa.entity; + +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.Objects; + +@Getter +@Entity +@Table(name = "post") +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Post extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id", nullable = false) + private Long id; + + @Column(nullable = false, length = 50) + private String title; + + @Column(nullable = false) + private String content; + + @ManyToOne + @JoinColumn(referencedColumnName = "id") + private User user; + + public void setUser(User user) { + if (Objects.nonNull(this.user)) { + this.user.getPostList().remove(this); + } + this.user = user; + user.getPostList().add(this); + } + + @Builder + private Post(String title, String content, User user) { + this.title = title; + this.content = content; + setUser(user); + this.createdBy = user.getName(); + } + + public void updateTitle(String title) { + this.title = title; + } + + public void updateContent(String content) { + this.content = content; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Post post = (Post) o; + return Objects.equals(id, post.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } +} \ No newline at end of file diff --git a/src/main/java/com/programmers/springbootboardjpa/entity/User.java b/src/main/java/com/programmers/springbootboardjpa/entity/User.java new file mode 100644 index 000000000..a957990b9 --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/entity/User.java @@ -0,0 +1,56 @@ +package com.programmers.springbootboardjpa.entity; + +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +@Entity +@Table(name = "users") +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class User extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id", nullable = false) + private long userId; + + @Column(nullable = false, length = 30) + private String name; + + @Column(nullable = false) + private int age; + + @Column + private String hobby; + + @OneToMany(mappedBy = "user") + private List postList = new ArrayList<>(); + + @Builder + private User(String name, int age, String hobby) { + this.name = name; + this.age = age; + this.hobby = hobby; + this.createdBy = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + User user = (User) o; + return userId == user.userId; + } + + @Override + public int hashCode() { + return Objects.hash(userId); + } +} diff --git a/src/main/java/com/programmers/springbootboardjpa/exception/ErrorMsg.java b/src/main/java/com/programmers/springbootboardjpa/exception/ErrorMsg.java new file mode 100644 index 000000000..61f42f697 --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/exception/ErrorMsg.java @@ -0,0 +1,17 @@ +package com.programmers.springbootboardjpa.exception; + +import lombok.Getter; + +@Getter +public enum ErrorMsg { + USER_NOT_FOUND(100, "유저가 존재하지 않습니다."), + POST_NOT_FOUND(101, "포스트가 존재하지 않습니다."); + + private final int code; + private final String message; + + ErrorMsg(int code, String message) { + this.code = code; + this.message = message; + } +} diff --git a/src/main/java/com/programmers/springbootboardjpa/exception/PostNotFoundException.java b/src/main/java/com/programmers/springbootboardjpa/exception/PostNotFoundException.java new file mode 100644 index 000000000..5a1db0117 --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/exception/PostNotFoundException.java @@ -0,0 +1,7 @@ +package com.programmers.springbootboardjpa.exception; + +public class PostNotFoundException extends RuntimeException { + public PostNotFoundException() { + super(ErrorMsg.POST_NOT_FOUND.getMessage()); + } +} diff --git a/src/main/java/com/programmers/springbootboardjpa/exception/UserNotFoundException.java b/src/main/java/com/programmers/springbootboardjpa/exception/UserNotFoundException.java new file mode 100644 index 000000000..1e15b738f --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/exception/UserNotFoundException.java @@ -0,0 +1,7 @@ +package com.programmers.springbootboardjpa.exception; + +public class UserNotFoundException extends RuntimeException { + public UserNotFoundException() { + super(ErrorMsg.USER_NOT_FOUND.getMessage()); + } +} diff --git a/src/main/java/com/programmers/springbootboardjpa/model/CommonResult.java b/src/main/java/com/programmers/springbootboardjpa/model/CommonResult.java new file mode 100644 index 000000000..65b602931 --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/model/CommonResult.java @@ -0,0 +1,28 @@ +package com.programmers.springbootboardjpa.model; + +import lombok.Getter; + +@Getter +public class CommonResult { + private final boolean isSuccess; + private final int code; + private final T data; + + private CommonResult(boolean isSuccess, int code, T data) { + this.isSuccess = isSuccess; + this.code = code; + this.data = data; + } + + public static CommonResult getSuccessResult() { + return new CommonResult<>(true, 0, "성공"); + } + + public static CommonResult getFailResult(int code, String message) { + return new CommonResult<>(false, code, message); + } + + public static CommonResult getResult(T data) { + return new CommonResult<>(true, 0, data); + } +} diff --git a/src/main/java/com/programmers/springbootboardjpa/repository/PostRepository.java b/src/main/java/com/programmers/springbootboardjpa/repository/PostRepository.java new file mode 100644 index 000000000..0c5a0c351 --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/repository/PostRepository.java @@ -0,0 +1,9 @@ +package com.programmers.springbootboardjpa.repository; + +import com.programmers.springbootboardjpa.entity.Post; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PostRepository extends JpaRepository { +} diff --git a/src/main/java/com/programmers/springbootboardjpa/repository/UserRepository.java b/src/main/java/com/programmers/springbootboardjpa/repository/UserRepository.java new file mode 100644 index 000000000..a0ea85c42 --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/repository/UserRepository.java @@ -0,0 +1,9 @@ +package com.programmers.springbootboardjpa.repository; + +import com.programmers.springbootboardjpa.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends JpaRepository { +} diff --git a/src/main/java/com/programmers/springbootboardjpa/service/PostService.java b/src/main/java/com/programmers/springbootboardjpa/service/PostService.java new file mode 100644 index 000000000..7ade5d8d9 --- /dev/null +++ b/src/main/java/com/programmers/springbootboardjpa/service/PostService.java @@ -0,0 +1,51 @@ +package com.programmers.springbootboardjpa.service; + +import com.programmers.springbootboardjpa.dto.PostServiceRequestDto; +import com.programmers.springbootboardjpa.dto.PostServiceResponseDto; +import com.programmers.springbootboardjpa.entity.Post; +import com.programmers.springbootboardjpa.entity.User; +import com.programmers.springbootboardjpa.exception.PostNotFoundException; +import com.programmers.springbootboardjpa.exception.UserNotFoundException; +import com.programmers.springbootboardjpa.repository.PostRepository; +import com.programmers.springbootboardjpa.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +@Transactional +public class PostService { + private final PostRepository postRepository; + private final UserRepository userRepository; + + public PostServiceResponseDto create(PostServiceRequestDto requestDto) { + User user = userRepository.findById(requestDto.getUserId()).orElseThrow(UserNotFoundException::new); + Post post = Post.builder() + .title(requestDto.getTitle()) + .content(requestDto.getContent()) + .user(user) + .build(); + return PostServiceResponseDto.of(postRepository.save(post)); + } + + public void update(Long postId, PostServiceRequestDto requestDto) { + Post post = postRepository.findById(postId).orElseThrow(PostNotFoundException::new); + post.updateTitle(requestDto.getTitle()); + post.updateContent(requestDto.getContent()); + } + + @Transactional(readOnly = true) + public PostServiceResponseDto findPostById(Long postId) { + return postRepository.findById(postId) + .map(PostServiceResponseDto::of).orElseThrow(PostNotFoundException::new); + } + + @Transactional(readOnly = true) + public Page findAll(Pageable pageable) { + return postRepository.findAll(pageable).map(PostServiceResponseDto::of); + } + +} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 000000000..45d26e2b4 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,14 @@ +spring: + h2: + console: + enabled: true + jpa: + generate-ddl: true + database: h2 + show-sql: true + open-in-view: false + properties: + hibernate: + dialect: org.hibernate.dialect.H2Dialect + hbm2ddl: + auto: create-drop \ No newline at end of file diff --git a/src/test/java/com/programmers/springbootboardjpa/controller/PostRestControllerTest.java b/src/test/java/com/programmers/springbootboardjpa/controller/PostRestControllerTest.java new file mode 100644 index 000000000..391cefb9a --- /dev/null +++ b/src/test/java/com/programmers/springbootboardjpa/controller/PostRestControllerTest.java @@ -0,0 +1,187 @@ +package com.programmers.springbootboardjpa.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.programmers.springbootboardjpa.dto.PostControllerCreateRequestDto; +import com.programmers.springbootboardjpa.dto.PostControllerUpdateRequestDto; +import com.programmers.springbootboardjpa.entity.Post; +import com.programmers.springbootboardjpa.entity.User; +import com.programmers.springbootboardjpa.repository.PostRepository; +import com.programmers.springbootboardjpa.repository.UserRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.restdocs.payload.JsonFieldType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.payload.PayloadDocumentation.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@AutoConfigureRestDocs +@Transactional +@DisplayName("PostRestController Test") +class PostRestControllerTest { + @Autowired + private MockMvc mvc; + @Autowired + private UserRepository userRepository; + @Autowired + private PostRepository postRepository; + @Autowired + private ObjectMapper objectMapper; + private User user; + + @BeforeEach + void init() { + user = userRepository.save(User.builder() + .name("username") + .age(26) + .hobby("testHobby") + .build()); + } + + @AfterEach + void tearDown() { + userRepository.deleteAll(); + } + + @Test + void createPost() throws Exception { + // Arrange + PostControllerCreateRequestDto requestDto = new PostControllerCreateRequestDto("title", "content", user.getUserId()); + var post = post("/posts").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(requestDto)); + // Act & Assert + mvc.perform(post) + .andExpect(status().isOk()) + .andDo(document("post-create", + requestFields( + fieldWithPath("title").type(JsonFieldType.STRING).description("제목"), + fieldWithPath("content").type(JsonFieldType.STRING).description("컨텐츠"), + fieldWithPath("userId").type(JsonFieldType.NUMBER).description("유저 ID")), + responseFields( + fieldWithPath("code").type(JsonFieldType.NUMBER).description("응답 코드"), + fieldWithPath("data.postId").type(JsonFieldType.NUMBER).description("포스트 ID"), + fieldWithPath("data.title").type(JsonFieldType.STRING).description("제목"), + fieldWithPath("data.content").type(JsonFieldType.STRING).description("컨텐츠"), + fieldWithPath("data.user.userId").type(JsonFieldType.NUMBER).description("유저 ID"), + fieldWithPath("data.user.name").type(JsonFieldType.STRING).description("유저 이름"), + fieldWithPath("data.user.age").type(JsonFieldType.NUMBER).description("유저 나이"), + fieldWithPath("data.user.hobby").type(JsonFieldType.STRING).description("유저 취미"), + fieldWithPath("data.createdAt").type(JsonFieldType.STRING).description("작성 시간"), + fieldWithPath("data.createdBy").type(JsonFieldType.STRING).description("작성자"), + fieldWithPath("success").type(JsonFieldType.BOOLEAN).description("성공 여부") + ))); + } + + @Test + void updatePost() throws Exception { + // Assert + var entity = postRepository.save(Post.builder() + .title("제목") + .content("컨텐츠") + .user(user) + .build()); + PostControllerUpdateRequestDto requestDto = new PostControllerUpdateRequestDto("title", "content"); + var post = post("/posts/{id}", entity.getId()).contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(requestDto)); + // Act & Assert + mvc.perform(post) + .andExpect(status().isOk()) + .andDo(document("post-update", + requestFields( + fieldWithPath("title").type(JsonFieldType.STRING).description("제목"), + fieldWithPath("content").type(JsonFieldType.STRING).description("컨텐츠")), + responseFields( + fieldWithPath("code").type(JsonFieldType.NUMBER).description("응답 코드"), + fieldWithPath("data").type(JsonFieldType.STRING).description("응답 메시지"), + fieldWithPath("success").type(JsonFieldType.BOOLEAN).description("성공 여부") + ))); + } + + @Test + void getPostById() throws Exception { + // Assert + var entity = postRepository.save(Post.builder() + .title("제목") + .content("컨텐츠") + .user(user) + .build()); + var get = get("/posts/{id}", entity.getId()); + // Act & Assert + mvc.perform(get) + .andExpect(status().isOk()) + .andDo(document("post-getById", + responseFields( + fieldWithPath("code").type(JsonFieldType.NUMBER).description("응답 코드"), + fieldWithPath("data.postId").type(JsonFieldType.NUMBER).description("포스트 ID"), + fieldWithPath("data.title").type(JsonFieldType.STRING).description("제목"), + fieldWithPath("data.content").type(JsonFieldType.STRING).description("컨텐츠"), + fieldWithPath("data.user.userId").type(JsonFieldType.NUMBER).description("유저 ID"), + fieldWithPath("data.user.name").type(JsonFieldType.STRING).description("유저 이름"), + fieldWithPath("data.user.age").type(JsonFieldType.NUMBER).description("유저 나이"), + fieldWithPath("data.user.hobby").type(JsonFieldType.STRING).description("유저 취미"), + fieldWithPath("data.createdAt").type(JsonFieldType.STRING).description("작성 시간"), + fieldWithPath("data.createdBy").type(JsonFieldType.STRING).description("작성자"), + fieldWithPath("success").type(JsonFieldType.BOOLEAN).description("성공 여부") + ))); + } + + @Test + void getAllPost() throws Exception { + // Assert + postRepository.save(Post.builder() + .title("제목") + .content("컨텐츠") + .user(user) + .build()); + var get = get("/posts") + .param("page", String.valueOf(0)) + .param("size", String.valueOf(10)); + // Act & Assert + mvc.perform(get) + .andExpect(status().isOk()) + .andDo(document("post-getAllPost", + responseFields( + fieldWithPath("code").type(JsonFieldType.NUMBER).description("응답 코드"), + fieldWithPath("data.content[].postId").type(JsonFieldType.NUMBER).description("포스트 ID"), + fieldWithPath("data.content[].title").type(JsonFieldType.STRING).description("제목"), + fieldWithPath("data.content[].content").type(JsonFieldType.STRING).description("컨텐츠"), + fieldWithPath("data.content[].user.userId").type(JsonFieldType.NUMBER).description("유저 ID"), + fieldWithPath("data.content[].user.name").type(JsonFieldType.STRING).description("유저 이름"), + fieldWithPath("data.content[].user.age").type(JsonFieldType.NUMBER).description("유저 나이"), + fieldWithPath("data.content[].user.hobby").type(JsonFieldType.STRING).description("유저 취미"), + fieldWithPath("data.content[].createdAt").type(JsonFieldType.STRING).description("작성 시간"), + fieldWithPath("data.content[].createdBy").type(JsonFieldType.STRING).description("작성자"), + fieldWithPath("data.pageable.pageNumber").type(JsonFieldType.NUMBER).description("페이지 번호"), + fieldWithPath("data.pageable.pageSize").type(JsonFieldType.NUMBER).description("페이지 크기"), + fieldWithPath("data.pageable.sort.empty").type(JsonFieldType.BOOLEAN).description("공백 여부"), + fieldWithPath("data.pageable.sort.sorted").type(JsonFieldType.BOOLEAN).description("정렬 여부(O)"), + fieldWithPath("data.pageable.sort.unsorted").type(JsonFieldType.BOOLEAN).description("정렬 여부 (X)"), + fieldWithPath("data.pageable.offset").type(JsonFieldType.NUMBER).description("오프셋"), + fieldWithPath("data.pageable.paged").type(JsonFieldType.BOOLEAN).description("페이지 여부(O)"), + fieldWithPath("data.pageable.unpaged").type(JsonFieldType.BOOLEAN).description("페이지 여부(X)"), + fieldWithPath("data.last").type(JsonFieldType.BOOLEAN).description("마지막 여부"), + fieldWithPath("data.totalPages").type(JsonFieldType.NUMBER).description("전체 페이지 "), + fieldWithPath("data.totalElements").type(JsonFieldType.NUMBER).description("전체 원소 개수"), + fieldWithPath("data.first").type(JsonFieldType.BOOLEAN).description("처음 여부"), + fieldWithPath("data.size").type(JsonFieldType.NUMBER).description("크기"), + fieldWithPath("data.number").type(JsonFieldType.NUMBER).description("번호"), + fieldWithPath("data.sort.empty").type(JsonFieldType.BOOLEAN).description("정렬 공백 여부"), + fieldWithPath("data.sort.sorted").type(JsonFieldType.BOOLEAN).description("정렬 여부(O)"), + fieldWithPath("data.sort.unsorted").type(JsonFieldType.BOOLEAN).description("정렬 여부(X)"), + fieldWithPath("data.numberOfElements").type(JsonFieldType.NUMBER).description("원소 갯수"), + fieldWithPath("data.empty").type(JsonFieldType.BOOLEAN).description("공백 여부"), + fieldWithPath("success").type(JsonFieldType.BOOLEAN).description("성공 여부") + ))); + } +} \ No newline at end of file diff --git a/src/test/java/com/programmers/springbootboardjpa/entity/PostTest.java b/src/test/java/com/programmers/springbootboardjpa/entity/PostTest.java new file mode 100644 index 000000000..cccc5d6d7 --- /dev/null +++ b/src/test/java/com/programmers/springbootboardjpa/entity/PostTest.java @@ -0,0 +1,46 @@ +package com.programmers.springbootboardjpa.entity; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("Test Post Entity") +class PostTest { + + private static User user; + + @BeforeEach + void init() { + // Arrange + String expectedName = "이름"; + int expectedAge = 26; + String expectedHobby = "취미"; + // Act + user = User.builder() + .name(expectedName) + .age(expectedAge) + .hobby(expectedHobby) + .build(); + } + + @Test + void testCreatePost(){ + // Arrange + String expectedTitle = "제목"; + String expectedContent = "내용"; + // Act + Post actualResult = Post.builder() + .title(expectedTitle) + .content(expectedContent) + .user(user) + .build(); + // Assert + assertThat(actualResult.getTitle()).isEqualTo(expectedTitle); + assertThat(actualResult.getContent()).isEqualTo(expectedContent); + assertThat(actualResult.getCreatedBy()).isEqualTo(user.getName()); + assertThat(user.getPostList()).contains(actualResult); + } + +} \ No newline at end of file diff --git a/src/test/java/com/programmers/springbootboardjpa/entity/UserTest.java b/src/test/java/com/programmers/springbootboardjpa/entity/UserTest.java new file mode 100644 index 000000000..2f4b8b0f7 --- /dev/null +++ b/src/test/java/com/programmers/springbootboardjpa/entity/UserTest.java @@ -0,0 +1,32 @@ +package com.programmers.springbootboardjpa.entity; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("User Entity Test") +class UserTest { + + @Test + void testCreateUserWithBuilder(){ + // Arrange + String expectedName = "이름"; + int expectedAge = 26; + String expectedHobby = "취미"; + // Act + User actualResult = User.builder() + .name(expectedName) + .age(expectedAge) + .hobby(expectedHobby) + .build(); + // Assert + assertThat(actualResult).isNotNull(); + assertThat(actualResult.getName()).isEqualTo(expectedName); + assertThat(actualResult.getAge()).isEqualTo(expectedAge); + assertThat(actualResult.getHobby()).isEqualTo(expectedHobby); + assertThat(actualResult.getCreatedBy()).isEqualTo(expectedName); + assertThat(actualResult.getPostList()).isEmpty(); + } + +} \ No newline at end of file diff --git a/src/test/java/com/programmers/springbootboardjpa/service/PostServiceTest.java b/src/test/java/com/programmers/springbootboardjpa/service/PostServiceTest.java new file mode 100644 index 000000000..53614d8b1 --- /dev/null +++ b/src/test/java/com/programmers/springbootboardjpa/service/PostServiceTest.java @@ -0,0 +1,116 @@ +package com.programmers.springbootboardjpa.service; + +import com.programmers.springbootboardjpa.dto.PostServiceRequestDto; +import com.programmers.springbootboardjpa.dto.PostServiceResponseDto; +import com.programmers.springbootboardjpa.entity.User; +import com.programmers.springbootboardjpa.repository.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.transaction.annotation.Transactional; + +import static org.assertj.core.api.Assertions.assertThat; + + +@SpringBootTest +@DisplayName("PostService Test") +@Transactional +class PostServiceTest { + @Autowired + private UserRepository userRepository; + @Autowired + private PostService postService; + + private static final String TITLE = "테스트 제목"; + private static final String CONTENT = "테스트 내용"; + + private PostServiceRequestDto requestDto; + private User user; + + + @BeforeEach + void init() { + user = userRepository.save(User.builder() + .name("username") + .age(26) + .hobby("testHobby") + .build()); + requestDto = PostServiceRequestDto.builder() + .title(TITLE) + .content(CONTENT) + .userId(user.getUserId()) + .build(); + } + + @Test + @DisplayName("포스트를 생성할 수 있다.") + void testCreatePostSuccess() { + // when + PostServiceResponseDto entity = postService.create(requestDto); + // then + assertThat(entity.getTitle()).isEqualTo(TITLE); + assertThat(entity.getContent()).isEqualTo(CONTENT); + assertThat(entity.getUser().getUserId()).isEqualTo(user.getUserId()); + assertThat(entity.getUser().getName()).isEqualTo(user.getName()); + assertThat(entity.getUser().getAge()).isEqualTo(user.getAge()); + assertThat(entity.getUser().getHobby()).isEqualTo(user.getHobby()); + } + + @Test + @DisplayName("포스트를 업데이트할 수 있다.") + void testUpdatePostSuccess() { + // given + final String UPDATE_TITLE = "업데이트 테스트 제목"; + final String UPDATE_CONTENT = "업데이트 테스트 내용"; + PostServiceRequestDto updateRequestDto = PostServiceRequestDto.builder() + .title(UPDATE_TITLE) + .content(UPDATE_CONTENT) + .userId(user.getUserId()) + .build(); + PostServiceResponseDto entity = postService.create(requestDto); + // when + postService.update(entity.getPostId(), updateRequestDto); + entity = postService.findPostById(entity.getPostId()); + // then + assertThat(entity.getTitle()).isEqualTo(UPDATE_TITLE); + assertThat(entity.getContent()).isEqualTo(UPDATE_CONTENT); + assertThat(entity.getUser().getUserId()).isEqualTo(user.getUserId()); + assertThat(entity.getUser().getName()).isEqualTo(user.getName()); + assertThat(entity.getUser().getAge()).isEqualTo(user.getAge()); + assertThat(entity.getUser().getHobby()).isEqualTo(user.getHobby()); + } + + @Test + @DisplayName("포스트를 아이디로 조회할 수 있다.") + void testFindById() { + // given + PostServiceResponseDto entity = postService.create(requestDto); + // when + PostServiceResponseDto findEntity = postService.findPostById(entity.getPostId()); + //then + assertThat(findEntity.getTitle()).isEqualTo(entity.getTitle()); + assertThat(findEntity.getContent()).isEqualTo(entity.getContent()); + assertThat(findEntity.getCreatedAt()).isEqualTo(entity.getCreatedAt()); + assertThat(findEntity.getCreatedBy()).isEqualTo(entity.getCreatedBy()); + assertThat(findEntity.getUser().getUserId()).isEqualTo(entity.getUser().getUserId()); + } + + @Test + @DisplayName("포스트를 페이징 처리를 통해 조회할 수 있다.") + void testFindByPaging() { + // given + Pageable pageable = Pageable.ofSize(10) + .withPage(0); + PostServiceResponseDto entity = postService.create(requestDto); + // when + Page pageEntity = postService.findAll(pageable); + // then + assertThat(pageEntity.getContent()).isNotEmpty(); + assertThat(pageEntity.getContent().get(0).getPostId()).isEqualTo(entity.getPostId()); + } + +} \ No newline at end of file