├── .gitignore ├── README.md ├── build.gradle ├── commons ├── common-model │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── kr │ │ └── dataportal │ │ └── invitation │ │ └── model │ │ └── member │ │ ├── InviteMember.java │ │ └── MemberStatus.java └── common-util │ ├── build.gradle │ └── src │ └── main │ └── java │ └── kr │ └── dataportal │ └── invitation │ └── util │ └── DateTimeUtils.java ├── docs └── overall-architecture.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── member-invitation-domain ├── build.gradle └── src │ ├── main │ └── java │ │ └── kr │ │ └── dataportal │ │ └── invitation │ │ ├── invitation │ │ ├── domain │ │ │ └── Invitation.java │ │ ├── exception │ │ │ ├── ExpiredInvitationException.java │ │ │ └── NotFoundInvitationException.java │ │ ├── service │ │ │ ├── AcceptInvitation.java │ │ │ ├── InvitationService.java │ │ │ ├── InviteWorkspace.java │ │ │ └── QueryInvitationByCode.java │ │ └── usecase │ │ │ ├── AcceptInvitationUseCase.java │ │ │ ├── InviteWorkspaceUseCase.java │ │ │ └── QueryInvitationByCodeUseCase.java │ │ └── member │ │ ├── domain │ │ └── Member.java │ │ ├── service │ │ └── QueryMemberById.java │ │ └── usecase │ │ └── QueryMemberByIdUseCase.java │ └── test │ └── java │ └── kr │ └── dataportal │ └── invitation │ └── invitation │ └── service │ ├── InvitationServiceTest.java │ └── InviteWorkspaceTest.java ├── member-invitation-infrastructure ├── persistence-database │ ├── build.gradle │ └── src │ │ ├── main │ │ ├── java │ │ │ └── kr │ │ │ │ └── dataportal │ │ │ │ └── invitation │ │ │ │ └── persistence │ │ │ │ ├── Persistence.java │ │ │ │ ├── config │ │ │ │ ├── BaseEntity.java │ │ │ │ └── JpaConfiguration.java │ │ │ │ ├── entity │ │ │ │ └── member │ │ │ │ │ └── MemberJpaEntity.java │ │ │ │ ├── repository │ │ │ │ └── member │ │ │ │ │ └── MemberRepository.java │ │ │ │ └── service │ │ │ │ └── member │ │ │ │ ├── MemberCommand.java │ │ │ │ ├── MemberQuery.java │ │ │ │ └── exception │ │ │ │ └── NotFoundMemberException.java │ │ └── resources │ │ │ └── application-persistence-database.yml │ │ └── test │ │ └── java │ │ └── kr │ │ └── dataportal │ │ └── invitation │ │ └── persistence │ │ └── service │ │ └── member │ │ ├── MemberCommandTest.java │ │ └── MemberQueryTest.java └── persistence-redis-adapter │ ├── build.gradle │ └── src │ └── main │ ├── java │ └── kr │ │ └── dataportal │ │ └── invitation │ │ └── persistence │ │ ├── config │ │ └── LocalRedisConfig.java │ │ └── service │ │ ├── LettuceRedisService.java │ │ └── RedisService.java │ └── resources │ └── application-persistence-redis-adapter.yml ├── member-invitation-interface ├── build.gradle └── src │ ├── main │ ├── java │ │ └── kr │ │ │ └── dataportal │ │ │ └── invitation │ │ │ ├── MemberInvitationApplication.java │ │ │ ├── api │ │ │ ├── invitation │ │ │ │ ├── InvitationRestController.java │ │ │ │ ├── dto │ │ │ │ │ ├── InvitationResponseDto.java │ │ │ │ │ └── InviteWorkspaceRequestDto.java │ │ │ │ └── mapper │ │ │ │ │ └── InvitationMapper.java │ │ │ └── member │ │ │ │ ├── MemberRestController.java │ │ │ │ ├── dto │ │ │ │ └── MemberResponseDto.java │ │ │ │ └── mapper │ │ │ │ └── MemberMapper.java │ │ │ └── config │ │ │ ├── ErrorResponseDto.java │ │ │ └── aop │ │ │ └── ApiRestControllerAdvice.java │ └── resources │ │ └── application.yml │ └── test │ └── resources │ └── http │ └── invitation.http └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | **/**/out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | 39 | /logs/ 40 | .DS_Store 41 | /build/ 42 | 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # member-invitation-java-springboot 2 | 3 | ## Context 4 | 5 | ### ACs - Biz 6 | 7 | - 그룹 매니저는 그룹에 참여자를 초대할 수 있습니다. 8 | - 사용자는 그룹 참여 초대 링크를 통해 그룹에 참여할 수 있습니다. 9 | - 초대 링크는 1회 사용 시 만료됩니다. 10 | 11 | ### ACs - Tech 12 | 13 | - 회원 초대 시 DB에 임시 회원을 생성하고 초대 링크를 발행합니다. 14 | - 생성 시에 회원의 이름, 전화번호, 이메일은 필수 값입니다. 15 | - 초대 링크 수락 시 임시 회원을 활성화하고 초대 링크를 만료합니다. 16 | - 회원의 인증/인가는 구현하지 않습니다. 17 | 18 | ## Challenge 19 | 20 | ### 휘발성 성격을 지닌 초대 링크를 어떻게 효율적으로 관리할 것인지? 21 | 22 | - 초대 링크 그 자체로는 영속성을 지닌 데이터가 아니라고 판단 23 | 1. 초대 링크 수락 시 링크 만료 24 | 2. 영구적으로 저장해두어 Business Metric으로 삼을만한 포인트도 존재하지 않음 -> 필요 시 로그로도 충분히 파악 가능 25 | 3. 추후 초대 링크 유효 기간 등 적용 고려 26 | - 초대 링크 저장소로 Redis 채택 27 | 1. 주기억장치를 활용하는 in-memory 저장소로 휘발성 데이터를 저장하기 적합 28 | 2. 초대 링크 유효 기간 -> TTL로 처리 가능 29 | - Redis가 아니어도 MongoDB TTL Index 등으로도 처리 가능할 것으로 보이지만 일반적으로 시스템이 커지며 BFF를 두는 구조가 되었을 때를 가정하고 설계 30 | - BFF Server <-> Domain Server 구조에서 MongoDB, MySQL 같은 영속성 저장소를 사용한다면 BFF -> Domain Server -> DB 구조로 네트워크 I/O와 DB 31 | I/O가 발생 32 | - 그러나 현재 구조에선 BFF Server -> Redis 단순 I/O만 발생하므로 보다 효율적 33 | 34 | ### 초대 링크와 관련된 여러 옵션이 추가된다면 어떻게 관리할 것인지? 35 | 36 | - ex) 초대 유효 기간, 초대 승인을 위한 패스워드, 초대장을 여러명이 사용할 수 있을 때 사용 가능한 횟수, 역할 등 37 | - 초대장 도메인 모델에 관한 Context Record를 두고 사용 38 | 39 | ```java 40 | public record Context( 41 | Duration duration 42 | ) { 43 | } 44 | ``` 45 | 46 | ## To-be, 발전 방향 47 | 48 | ### 다수의 서버, 인스턴스에서 동작하더라도 문제가 없는 시스템으로 개선 49 | 50 | - 현재 구조에서는 동일한 페이로드로 회원 초대 API를 짧은 간격으로 다수 호출하는 경우 같은 회원에 대한 계정 정보가 여러개 생성될 수 있는 가능성이 존재 51 | - 이를 해결하기 위해 임시 회원 생성 ~ 초대 링크 발행의 과정을 하나의 트랜잭션으로 묶고 비관적 락/낙관적 락을 채택할 필요성이 존재 52 | - DB 레벨의 락의 경우 성능에 큰 영향을 미치기 때문에 애플리케이션 레벨의 분산락 등을 고려해볼 필요성도 있음. 53 | - https://github.com/heli-os/kotlin-springboot-distributed-lock 54 | 55 | ### 그 외 56 | 57 | - DB I/O 인스턴스와 API 요청 수신 인스턴스를 분리해 네트워크 부하, I/O 부하 분리 58 | - DB I/O 인스턴스에 문제가 생겼을 때를 대비하여 두 인스턴스 사이 Queue를 두어 Retry 등 데이터 정합성 유지를 위한 로직 추가 59 | - 인증/인가 로직 추가 구현 -> Workspace/Collaborator/Member Auditing ContextHolder 60 | 61 | --- 62 | 63 | ## Overall Architecture 64 | 65 | ![overall-architecture](./docs/overall-architecture.png) 66 | 67 | ## APIs & Data Model 68 | 69 | ### Data Model 70 | 71 | **InvitationResponseDto** 72 | 73 | ``` 74 | { 75 | "workspaceId": 0, 76 | "memberId": 0, 77 | "expiresAt": 0, // Unix Time(epochMillis) 78 | "code": "String" 79 | } 80 | ``` 81 | 82 | **MemberResponseDto** 83 | 84 | ``` 85 | { 86 | "id": 0, 87 | "createdAt": 0, // Unix Time(epochMillis) 88 | "lastModifiedAt": 0, // Unix Time(epochMillis) 89 | "name": "String", 90 | "phoneNumber": "String", 91 | "email": "String", 92 | "status": "String" // CANDIDATE, ACTIVATE, DEACTIVATE 93 | } 94 | ``` 95 | 96 | ### 그룹(워크스페이스) 초대 API 97 | 98 | POST `/api/v1/workspace/{workspaceId}/invitation` 99 | 100 | **Request Body** 101 | 102 | ``` 103 | { 104 | "inviteMemberName": "String", 105 | "inviteMemberPhoneNumber": "String", 106 | "inviteMemberEmail": "String" 107 | } 108 | ``` 109 | 110 | **Response Body** 111 | 112 | ``` 113 | DataModel#InvitationResponseDto 114 | ``` 115 | 116 | ### 발급된 초대장 조회 API 117 | 118 | GET `/api/v1/invitation/{code}` 119 | 120 | **Response Body** 121 | 122 | ``` 123 | DataModel#InvitationResponseDto 124 | ``` 125 | 126 | ### 초대 승낙 API 127 | 128 | POST `/api/v1/invitation/{code}/accept` 129 | 130 | **Response Body** 131 | 132 | ``` 133 | DataModel#InvitationResponseDto 134 | ``` 135 | 136 | ### 기존에 가입된 회원 조회 API 137 | 138 | GET `/api/v1/member/{memberId}` 139 | 140 | **Response Body** 141 | 142 | ``` 143 | DataModel#MemberResponseDto 144 | ``` 145 | 146 | --- 147 | 148 | ## Appendix 149 | 150 | - 주요 도메인 컴포넌트에 대한 테스트 코드만 작성하고, E2E 테스트는 별도로 작성하지 않았습니다. 151 | - 에러와 예외를 어떻게 처리할 것인지에 대한 전체적인 시스템을 정의하여야 합니다. 152 | - 추후 logback rollingPolicy 적용이 필요합니다. 153 | - last updated at: 2022-11-30 154 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '2.7.6' apply(false) 4 | id 'io.spring.dependency-management' version '1.0.15.RELEASE' apply(false) 5 | } 6 | 7 | allprojects { 8 | apply plugin: 'java' 9 | 10 | group = 'kr.dataportal' 11 | version = '0.0.1-SNAPSHOT' 12 | sourceCompatibility = '17' 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | } 18 | 19 | subprojects { 20 | apply plugin: 'org.springframework.boot' 21 | apply plugin: 'io.spring.dependency-management' 22 | 23 | configurations { 24 | compileOnly { 25 | extendsFrom annotationProcessor 26 | } 27 | } 28 | 29 | dependencies { 30 | // https://mvnrepository.com/artifact/com.google.guava/guava 31 | implementation 'com.google.guava:guava:31.1-jre' 32 | 33 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 34 | } 35 | 36 | tasks.named('test') { 37 | useJUnitPlatform() 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /commons/common-model/build.gradle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/heli-os/member-invitation-java-springboot/3d2ead5de3c38437667814699890ccd0cff60f1d/commons/common-model/build.gradle -------------------------------------------------------------------------------- /commons/common-model/src/main/java/kr/dataportal/invitation/model/member/InviteMember.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.model.member; 2 | 3 | /** 4 | * @author Heli 5 | * Created on 2022. 11. 30 6 | */ 7 | public record InviteMember( 8 | String name, 9 | String phoneNumber, 10 | String email 11 | ) { 12 | } 13 | -------------------------------------------------------------------------------- /commons/common-model/src/main/java/kr/dataportal/invitation/model/member/MemberStatus.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.model.member; 2 | 3 | /** 4 | * @author Heli 5 | * Created on 2022. 11. 30 6 | */ 7 | public enum MemberStatus { 8 | CANDIDATE("그룹 초대 등을 통한 임시 가입 상태"), 9 | ACTIVATE("계정 활성화 상태"), 10 | DEACTIVATE("계정 탈퇴 상태"); 11 | 12 | private final String description; 13 | 14 | MemberStatus(String description) { 15 | this.description = description; 16 | } 17 | 18 | public String getDescription() { 19 | return description; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /commons/common-util/build.gradle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/heli-os/member-invitation-java-springboot/3d2ead5de3c38437667814699890ccd0cff60f1d/commons/common-util/build.gradle -------------------------------------------------------------------------------- /commons/common-util/src/main/java/kr/dataportal/invitation/util/DateTimeUtils.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.util; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.ZoneId; 5 | import java.time.ZoneOffset; 6 | 7 | /** 8 | * @author Heli 9 | * Created on 2022. 11. 30 10 | */ 11 | public class DateTimeUtils { 12 | private static final ZoneId KST = ZoneOffset.ofHours(9); 13 | 14 | public static long toEpochMillis(final LocalDateTime localDateTime) { 15 | return localDateTime.atZone(KST).toInstant().toEpochMilli(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /docs/overall-architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/heli-os/member-invitation-java-springboot/3d2ead5de3c38437667814699890ccd0cff60f1d/docs/overall-architecture.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/heli-os/member-invitation-java-springboot/3d2ead5de3c38437667814699890ccd0cff60f1d/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /member-invitation-domain/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation project(':commons:common-model') 3 | implementation project(':member-invitation-infrastructure:persistence-database') 4 | implementation project(':member-invitation-infrastructure:persistence-redis-adapter') 5 | 6 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 7 | 8 | // https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 9 | implementation 'org.apache.commons:commons-lang3:3.12.0' 10 | } 11 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/invitation/domain/Invitation.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.invitation.domain; 2 | 3 | import org.apache.commons.lang3.RandomStringUtils; 4 | 5 | import java.time.Duration; 6 | import java.time.LocalDateTime; 7 | 8 | /** 9 | * @author Heli 10 | * Created on 2022. 11. 30 11 | */ 12 | public record Invitation( 13 | Target target, 14 | LocalDateTime expiresAt, 15 | String code 16 | ) { 17 | 18 | private static final long DEFAULT_EXPIRED_DAYS = 1L; 19 | public static final Context DEFAULT_CONTEXT = new Context(Duration.ofDays(DEFAULT_EXPIRED_DAYS)); 20 | private static final int INVITE_CODE_LENGTH = 32; 21 | 22 | public static Invitation create(final Target target, final Context context) { 23 | LocalDateTime expiresAt = LocalDateTime.now().plusMinutes(context.duration.toMinutes()); 24 | String code = RandomStringUtils.randomAlphanumeric(INVITE_CODE_LENGTH); 25 | return new Invitation(target, expiresAt, code); 26 | } 27 | 28 | public boolean isUsableAt(final LocalDateTime now) { 29 | return now.isBefore(expiresAt); 30 | } 31 | 32 | public Duration remainDuration(final LocalDateTime now) { 33 | return Duration.between(now, expiresAt); 34 | } 35 | 36 | public record Target( 37 | long workspaceId, 38 | long memberId 39 | ) { 40 | } 41 | 42 | /** 43 | * Invitation 관련 여러가지 설정을 묶어 관리하는 Context 44 | * 초대 유효 기간, 초대 승인을 위한 패스워드, 역할 등을 관리 45 | */ 46 | public record Context( 47 | Duration duration 48 | ) { 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/invitation/exception/ExpiredInvitationException.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.invitation.exception; 2 | 3 | import kr.dataportal.invitation.invitation.domain.Invitation; 4 | 5 | /** 6 | * @author Heli 7 | * Created on 2022. 11. 30 8 | */ 9 | public class ExpiredInvitationException extends RuntimeException { 10 | private static final String MESSAGE_FORMAT = "만료된 Invitation [invitation=%s]"; 11 | 12 | public ExpiredInvitationException(final Invitation invitation) { 13 | super(String.format(MESSAGE_FORMAT, invitation)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/invitation/exception/NotFoundInvitationException.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.invitation.exception; 2 | 3 | /** 4 | * @author Heli 5 | * Created on 2022. 11. 30 6 | */ 7 | public class NotFoundInvitationException extends RuntimeException { 8 | 9 | private static final String MESSAGE_FORMAT = "Invitation 조회 실패 [invitationCode=%s]"; 10 | 11 | public NotFoundInvitationException(final String invitationCode) { 12 | super(String.format(MESSAGE_FORMAT, invitationCode)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/invitation/service/AcceptInvitation.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.invitation.service; 2 | 3 | import kr.dataportal.invitation.invitation.domain.Invitation; 4 | import kr.dataportal.invitation.invitation.usecase.AcceptInvitationUseCase; 5 | import kr.dataportal.invitation.persistence.service.member.MemberCommand; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | /** 10 | * @author Heli 11 | * Created on 2022. 11. 30 12 | */ 13 | @Service 14 | @Transactional 15 | public class AcceptInvitation implements AcceptInvitationUseCase { 16 | 17 | private final InvitationService invitationService; 18 | private final MemberCommand memberCommand; 19 | 20 | public AcceptInvitation(final InvitationService invitationService, final MemberCommand memberCommand) { 21 | this.invitationService = invitationService; 22 | this.memberCommand = memberCommand; 23 | } 24 | 25 | @Override 26 | public Invitation command(final Command command) { 27 | Invitation invitation = invitationService.getByInvitationCode(command.invitationCode()); 28 | Invitation.Target target = invitation.target(); 29 | 30 | memberCommand.activate(target.memberId()); 31 | invitationService.expireInvitation(invitation); 32 | return invitation; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/invitation/service/InvitationService.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.invitation.service; 2 | 3 | import kr.dataportal.invitation.invitation.domain.Invitation; 4 | import kr.dataportal.invitation.invitation.exception.ExpiredInvitationException; 5 | import kr.dataportal.invitation.invitation.exception.NotFoundInvitationException; 6 | import kr.dataportal.invitation.persistence.service.RedisService; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.time.Duration; 10 | import java.time.LocalDateTime; 11 | import java.util.Optional; 12 | 13 | /** 14 | * @author Heli 15 | * Created on 2022. 11. 30 16 | */ 17 | @Service 18 | public class InvitationService { 19 | 20 | private final RedisService redisService; 21 | 22 | public InvitationService(final RedisService redisService) { 23 | this.redisService = redisService; 24 | } 25 | 26 | public void issueInvitation(final Invitation invitation) { 27 | saveInvitation(invitation); 28 | } 29 | 30 | public void useInvitation(final Invitation invitation) { 31 | if (!invitation.isUsableAt(LocalDateTime.now())) { 32 | throw new ExpiredInvitationException(invitation); 33 | } 34 | deleteInvitation(invitation); 35 | } 36 | 37 | public void expireInvitation(final Invitation invitation) { 38 | deleteInvitation(invitation); 39 | } 40 | 41 | public Optional getByTarget(final Invitation.Target target) { 42 | String invitationRedisKey = invitationRedisKey(target); 43 | return redisService.get(invitationRedisKey, Invitation.class) 44 | .filter(invitation -> invitation.isUsableAt(LocalDateTime.now())); 45 | } 46 | 47 | public Invitation getByInvitationCode(final String invitationCode) { 48 | String targetRedisKey = targetRedisKey(invitationCode); 49 | // TODO Exception 고도화 50 | Invitation.Target target = redisService.get(targetRedisKey, Invitation.Target.class).orElseThrow(); 51 | return getByTarget(target).orElseThrow(() -> new NotFoundInvitationException(invitationCode)); 52 | } 53 | 54 | private void saveInvitation(final Invitation invitation) { 55 | Duration ttl = invitation.remainDuration(LocalDateTime.now()); 56 | 57 | String invitationRedisKey = invitationRedisKey(invitation.target()); 58 | String targetRedisKey = targetRedisKey(invitation.code()); 59 | 60 | redisService.set(invitationRedisKey, invitation, ttl); 61 | redisService.set(targetRedisKey, invitation.target(), ttl); 62 | } 63 | 64 | private void deleteInvitation(final Invitation invitation) { 65 | String invitationRedisKey = invitationRedisKey(invitation.target()); 66 | String targetRedisKey = targetRedisKey(invitation.code()); 67 | 68 | redisService.delete(invitationRedisKey); 69 | redisService.delete(targetRedisKey); 70 | } 71 | 72 | /** 73 | * Target(WorkspaceId + MemberId) -> Invitation 조회를 위한 키 74 | */ 75 | private String invitationRedisKey(final Invitation.Target target) { 76 | return "invitation:target:" + target; 77 | } 78 | 79 | /** 80 | * InvitationCode -> Target(WorkspaceId + MemberId) 조회를 위한 키 81 | */ 82 | private String targetRedisKey(final String invitationCode) { 83 | return "invitation:code:" + invitationCode; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/invitation/service/InviteWorkspace.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.invitation.service; 2 | 3 | import kr.dataportal.invitation.invitation.domain.Invitation; 4 | import kr.dataportal.invitation.invitation.usecase.InviteWorkspaceUseCase; 5 | import kr.dataportal.invitation.persistence.entity.member.MemberJpaEntity; 6 | import kr.dataportal.invitation.persistence.service.member.MemberCommand; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | /** 11 | * @author Heli 12 | * Created on 2022. 11. 30 13 | */ 14 | @Service 15 | @Transactional 16 | public class InviteWorkspace implements InviteWorkspaceUseCase { 17 | 18 | private final InvitationService invitationService; 19 | private final MemberCommand memberCommand; 20 | 21 | public InviteWorkspace(final InvitationService invitationService, final MemberCommand memberCommand) { 22 | this.invitationService = invitationService; 23 | this.memberCommand = memberCommand; 24 | } 25 | 26 | @Override 27 | public Invitation command(final Command command) { 28 | // TODO member in workspace 검증 (Spring Security 레벨에서 인증/인가 처리 -> Workspace/Collaborator/Member Auditing ContextHolder) 29 | 30 | MemberJpaEntity candidateMemberJpaEntity = memberCommand.newCandidate(command.inviteMember()); 31 | Invitation.Target target = command.target(candidateMemberJpaEntity.getId()); 32 | 33 | invitationService.getByTarget(target) 34 | .ifPresent(invitationService::expireInvitation); 35 | 36 | Invitation invitation = Invitation.create(target, Invitation.DEFAULT_CONTEXT); 37 | invitationService.issueInvitation(invitation); 38 | return invitation; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/invitation/service/QueryInvitationByCode.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.invitation.service; 2 | 3 | import kr.dataportal.invitation.invitation.domain.Invitation; 4 | import kr.dataportal.invitation.invitation.usecase.QueryInvitationByCodeUseCase; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.transaction.annotation.Transactional; 7 | 8 | /** 9 | * @author Heli 10 | * Created on 2022. 11. 30 11 | */ 12 | @Service 13 | @Transactional(readOnly = true) 14 | public class QueryInvitationByCode implements QueryInvitationByCodeUseCase { 15 | 16 | private final InvitationService invitationService; 17 | 18 | public QueryInvitationByCode(final InvitationService invitationService) { 19 | this.invitationService = invitationService; 20 | } 21 | 22 | @Override 23 | public Invitation query(final Query query) { 24 | return invitationService.getByInvitationCode(query.code()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/invitation/usecase/AcceptInvitationUseCase.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.invitation.usecase; 2 | 3 | import kr.dataportal.invitation.invitation.domain.Invitation; 4 | 5 | /** 6 | * @author Heli 7 | * Created on 2022. 11. 30 8 | */ 9 | public interface AcceptInvitationUseCase { 10 | 11 | 12 | Invitation command(final Command command); 13 | 14 | record Command( 15 | String invitationCode 16 | ) { 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/invitation/usecase/InviteWorkspaceUseCase.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.invitation.usecase; 2 | 3 | import kr.dataportal.invitation.invitation.domain.Invitation; 4 | import kr.dataportal.invitation.model.member.InviteMember; 5 | 6 | /** 7 | * @author Heli 8 | * Created on 2022. 11. 30 9 | */ 10 | public interface InviteWorkspaceUseCase { 11 | 12 | 13 | Invitation command(final Command command); 14 | 15 | record Command( 16 | long workspaceId, 17 | InviteMember inviteMember 18 | ) { 19 | public Invitation.Target target(final long memberId) { 20 | return new Invitation.Target(workspaceId, memberId); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/invitation/usecase/QueryInvitationByCodeUseCase.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.invitation.usecase; 2 | 3 | import kr.dataportal.invitation.invitation.domain.Invitation; 4 | 5 | /** 6 | * @author Heli 7 | * Created on 2022. 11. 30 8 | */ 9 | public interface QueryInvitationByCodeUseCase { 10 | 11 | Invitation query(final Query query); 12 | 13 | record Query( 14 | String code 15 | ) { 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/member/domain/Member.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.member.domain; 2 | 3 | import kr.dataportal.invitation.model.member.MemberStatus; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | /** 8 | * @author Heli 9 | * Created on 2022. 11. 30 10 | */ 11 | public record Member( 12 | long id, 13 | LocalDateTime createdAt, 14 | LocalDateTime lastModifiedAt, 15 | String name, 16 | String phoneNumber, 17 | String email, 18 | MemberStatus status 19 | ) { 20 | } 21 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/member/service/QueryMemberById.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.member.service; 2 | 3 | import kr.dataportal.invitation.member.domain.Member; 4 | import kr.dataportal.invitation.member.usecase.QueryMemberByIdUseCase; 5 | import kr.dataportal.invitation.persistence.entity.member.MemberJpaEntity; 6 | import kr.dataportal.invitation.persistence.service.member.MemberQuery; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | /** 11 | * @author Heli 12 | * Created on 2022. 11. 30 13 | */ 14 | @Service 15 | @Transactional(readOnly = true) 16 | public class QueryMemberById implements QueryMemberByIdUseCase { 17 | 18 | private final MemberQuery memberQuery; 19 | 20 | public QueryMemberById(final MemberQuery memberQuery) { 21 | this.memberQuery = memberQuery; 22 | } 23 | 24 | @Override 25 | public Member query(final Query query) { 26 | MemberJpaEntity memberJpaEntity = memberQuery.findById(query.memberId()); 27 | return new Member( 28 | memberJpaEntity.getId(), 29 | memberJpaEntity.getCreatedAt(), 30 | memberJpaEntity.getLastModifiedAt(), 31 | memberJpaEntity.getName(), 32 | memberJpaEntity.getPhoneNumber(), 33 | memberJpaEntity.getEmail(), 34 | memberJpaEntity.getStatus() 35 | ); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /member-invitation-domain/src/main/java/kr/dataportal/invitation/member/usecase/QueryMemberByIdUseCase.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.member.usecase; 2 | 3 | import kr.dataportal.invitation.member.domain.Member; 4 | 5 | /** 6 | * @author Heli 7 | * Created on 2022. 11. 30 8 | */ 9 | public interface QueryMemberByIdUseCase { 10 | 11 | Member query(final Query query); 12 | 13 | record Query( 14 | long memberId 15 | ) { 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /member-invitation-domain/src/test/java/kr/dataportal/invitation/invitation/service/InvitationServiceTest.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.invitation.service; 2 | 3 | import kr.dataportal.invitation.invitation.domain.Invitation; 4 | import kr.dataportal.invitation.invitation.exception.ExpiredInvitationException; 5 | import kr.dataportal.invitation.persistence.service.RedisService; 6 | import org.junit.jupiter.api.*; 7 | import org.mockito.Mock; 8 | import org.mockito.MockitoAnnotations; 9 | 10 | import java.time.Duration; 11 | import java.time.LocalDateTime; 12 | import java.util.Optional; 13 | 14 | import static org.assertj.core.api.AssertionsForClassTypes.assertThat; 15 | import static org.junit.jupiter.api.Assertions.fail; 16 | import static org.mockito.ArgumentMatchers.any; 17 | import static org.mockito.ArgumentMatchers.eq; 18 | import static org.mockito.Mockito.*; 19 | 20 | /** 21 | * @author Heli 22 | * Created on 2022. 11. 30 23 | */ 24 | @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) 25 | class InvitationServiceTest { 26 | 27 | private final Invitation DEFAULT_INVITATION = Invitation.create(new Invitation.Target(1L, 2L), Invitation.DEFAULT_CONTEXT); 28 | private final String DEFAULT_INVITATION_REDIS_KEY = "invitation:target:" + DEFAULT_INVITATION.target(); 29 | private final String DEFAULT_TARGET_REDIS_KEY = "invitation:code:" + DEFAULT_INVITATION.code(); 30 | @Mock 31 | private RedisService redisService; 32 | 33 | private InvitationService sut; 34 | 35 | @BeforeEach 36 | void init() { 37 | MockitoAnnotations.openMocks(this); 38 | sut = new InvitationService(redisService); 39 | } 40 | 41 | @Test 42 | void 초대장을_발행할_수_있다() { 43 | sut.issueInvitation(DEFAULT_INVITATION); 44 | verify(redisService, times(1)).set(eq(DEFAULT_INVITATION_REDIS_KEY), eq(DEFAULT_INVITATION), any(Duration.class)); 45 | verify(redisService, times(1)).set(eq(DEFAULT_TARGET_REDIS_KEY), eq(DEFAULT_INVITATION.target()), any(Duration.class)); 46 | } 47 | 48 | @Test 49 | void 만료된_초대장_사용_시도_시_ExpiredInvitationException_예외_발생() { 50 | Invitation zeroDurationInvitation = Invitation.create(new Invitation.Target(1L, 2L), new Invitation.Context(Duration.ZERO)); 51 | Assertions.assertThrows( 52 | ExpiredInvitationException.class, 53 | () -> sut.useInvitation(zeroDurationInvitation) 54 | ); 55 | } 56 | 57 | @Test 58 | void 유효한_초대장_사용_시도_시_초대장_만료() { 59 | sut.useInvitation(DEFAULT_INVITATION); 60 | verify(redisService, times(1)).delete(eq(DEFAULT_INVITATION_REDIS_KEY)); 61 | verify(redisService, times(1)).delete(eq(DEFAULT_TARGET_REDIS_KEY)); 62 | } 63 | 64 | @Test 65 | void 초대장을_만료_시킬_수_있다() { 66 | sut.expireInvitation(DEFAULT_INVITATION); 67 | verify(redisService, times(1)).delete(eq(DEFAULT_INVITATION_REDIS_KEY)); 68 | verify(redisService, times(1)).delete(eq(DEFAULT_TARGET_REDIS_KEY)); 69 | } 70 | 71 | @Test 72 | void Invitation_Target_으로_Invitation_을_얻어올_수_있다() { 73 | when(redisService.get(DEFAULT_INVITATION_REDIS_KEY, Invitation.class)).thenReturn(Optional.of(DEFAULT_INVITATION)); 74 | 75 | Invitation actual = sut.getByTarget(DEFAULT_INVITATION.target()) 76 | .orElseGet(() -> fail("Invitation must not be null")); 77 | 78 | assertThat(actual.code()).isEqualTo(DEFAULT_INVITATION.code()); 79 | assertThat(actual.target().workspaceId()).isEqualTo(1L); 80 | assertThat(actual.target().memberId()).isEqualTo(2L); 81 | assertThat(actual.isUsableAt(LocalDateTime.now())).isTrue(); 82 | verify(redisService, times(1)).get(eq(DEFAULT_INVITATION_REDIS_KEY), eq(Invitation.class)); 83 | } 84 | 85 | @Test 86 | void invitationCode_로_Invitation_Target_을_얻어올_수_있다() { 87 | when(redisService.get(DEFAULT_TARGET_REDIS_KEY, Invitation.Target.class)).thenReturn(Optional.of(DEFAULT_INVITATION.target())); 88 | when(redisService.get(DEFAULT_INVITATION_REDIS_KEY, Invitation.class)).thenReturn(Optional.of(DEFAULT_INVITATION)); 89 | 90 | Invitation actual = sut.getByInvitationCode(DEFAULT_INVITATION.code()); 91 | 92 | assertThat(actual.code()).isEqualTo(DEFAULT_INVITATION.code()); 93 | assertThat(actual.target().workspaceId()).isEqualTo(1L); 94 | assertThat(actual.target().memberId()).isEqualTo(2L); 95 | assertThat(actual.isUsableAt(LocalDateTime.now())).isTrue(); 96 | verify(redisService, times(1)).get(eq(DEFAULT_TARGET_REDIS_KEY), eq(Invitation.Target.class)); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /member-invitation-domain/src/test/java/kr/dataportal/invitation/invitation/service/InviteWorkspaceTest.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.invitation.service; 2 | 3 | import kr.dataportal.invitation.invitation.domain.Invitation; 4 | import kr.dataportal.invitation.invitation.usecase.InviteWorkspaceUseCase; 5 | import kr.dataportal.invitation.model.member.InviteMember; 6 | import kr.dataportal.invitation.persistence.entity.member.MemberJpaEntity; 7 | import kr.dataportal.invitation.persistence.service.member.MemberCommand; 8 | import org.junit.jupiter.api.BeforeEach; 9 | import org.junit.jupiter.api.DisplayNameGeneration; 10 | import org.junit.jupiter.api.DisplayNameGenerator; 11 | import org.junit.jupiter.api.Test; 12 | import org.mockito.Mock; 13 | import org.mockito.MockitoAnnotations; 14 | 15 | import java.time.LocalDateTime; 16 | import java.util.Optional; 17 | 18 | import static kr.dataportal.invitation.invitation.domain.Invitation.DEFAULT_CONTEXT; 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | import static org.mockito.Mockito.*; 21 | 22 | /** 23 | * @author Heli 24 | * Created on 2022. 11. 30 25 | */ 26 | @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) 27 | class InviteWorkspaceTest { 28 | 29 | private final InviteWorkspaceUseCase.Command command = new InviteWorkspaceUseCase.Command( 30 | 1L, 31 | new InviteMember("Heli", "010-1111-2222", "heli@example.com") 32 | ); 33 | private final Invitation.Target target = command.target(2L); 34 | private final Invitation invitation = Invitation.create(target, DEFAULT_CONTEXT); 35 | private final MemberJpaEntity memberJpaEntity = MemberJpaEntity.newCandidate("Heli", "010-1111-2222", "heli@example.com").apply(2L, LocalDateTime.now()); 36 | @Mock 37 | private InvitationService invitationService; 38 | @Mock 39 | private MemberCommand memberCommand; 40 | private InviteWorkspaceUseCase sut; 41 | 42 | @BeforeEach 43 | void init() { 44 | MockitoAnnotations.openMocks(this); 45 | when(memberCommand.newCandidate(command.inviteMember())).thenReturn(memberJpaEntity); 46 | sut = new InviteWorkspace(invitationService, memberCommand); 47 | } 48 | 49 | @Test 50 | void 기존에_등록된_초대장이_있다면_만료_후_재생성한다() { 51 | when(invitationService.getByTarget(command.target(2L))) 52 | .thenReturn(Optional.of(invitation)); 53 | 54 | Invitation actual = sut.command(command); 55 | 56 | assertThat(actual.code()).isNotEqualTo(invitation.code()); 57 | assertThat(actual.expiresAt()).isNotEqualTo(invitation.expiresAt()); 58 | assertThat(actual.target().workspaceId()).isEqualTo(1L); 59 | assertThat(actual.target().memberId()).isEqualTo(2L); 60 | verify(invitationService, times(1)).expireInvitation(invitation); 61 | verify(invitationService, times(1)).issueInvitation(actual); 62 | } 63 | 64 | @Test 65 | void 기존에_등록된_초대장이_없다면_신규_생성한다() { 66 | when(invitationService.getByTarget(command.target(2L))) 67 | .thenReturn(Optional.empty()); 68 | 69 | Invitation actual = sut.command(command); 70 | 71 | assertThat(actual.code()).isNotNull(); 72 | assertThat(actual.expiresAt()).isNotNull(); 73 | assertThat(actual.target().workspaceId()).isEqualTo(1L); 74 | assertThat(actual.target().memberId()).isEqualTo(2L); 75 | verify(invitationService, times(0)).expireInvitation(invitation); 76 | verify(invitationService, times(1)).issueInvitation(actual); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-database/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation project(':commons:common-model') 3 | 4 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 5 | runtimeOnly 'com.h2database:h2' 6 | } 7 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-database/src/main/java/kr/dataportal/invitation/persistence/Persistence.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence; 2 | 3 | /** 4 | * @author Heli 5 | * Created on 2022. 11. 30 6 | */ 7 | public interface Persistence { 8 | } 9 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-database/src/main/java/kr/dataportal/invitation/persistence/config/BaseEntity.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence.config; 2 | 3 | import com.google.common.annotations.VisibleForTesting; 4 | 5 | import javax.persistence.*; 6 | import java.time.LocalDateTime; 7 | 8 | /** 9 | * @author Heli 10 | * Created on 2022. 11. 30 11 | */ 12 | @MappedSuperclass 13 | public abstract class BaseEntity> { 14 | 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private Long id = null; 18 | 19 | @Column(updatable = false) 20 | private LocalDateTime createdAt; 21 | 22 | private LocalDateTime lastModifiedAt; 23 | 24 | @PrePersist 25 | void prePersist() { 26 | LocalDateTime now = LocalDateTime.now(); 27 | createdAt = now; 28 | lastModifiedAt = now; 29 | } 30 | 31 | @PreUpdate 32 | void preUpdate() { 33 | lastModifiedAt = LocalDateTime.now(); 34 | } 35 | 36 | public Long getId() { 37 | return id; 38 | } 39 | 40 | public LocalDateTime getCreatedAt() { 41 | return createdAt; 42 | } 43 | 44 | public LocalDateTime getLastModifiedAt() { 45 | return lastModifiedAt; 46 | } 47 | 48 | @SuppressWarnings("unchecked") 49 | @VisibleForTesting 50 | public T apply(final long id, final LocalDateTime now) { 51 | this.id = id; 52 | this.createdAt = now; 53 | this.lastModifiedAt = now; 54 | return (T) this; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-database/src/main/java/kr/dataportal/invitation/persistence/config/JpaConfiguration.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence.config; 2 | 3 | import kr.dataportal.invitation.persistence.Persistence; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; 6 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 7 | 8 | /** 9 | * @author Heli 10 | * Created on 2022. 11. 30 11 | */ 12 | @Configuration 13 | @EnableJpaAuditing 14 | @EnableJpaRepositories( 15 | basePackageClasses = {Persistence.class} 16 | ) 17 | public class JpaConfiguration { 18 | } 19 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-database/src/main/java/kr/dataportal/invitation/persistence/entity/member/MemberJpaEntity.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence.entity.member; 2 | 3 | import kr.dataportal.invitation.model.member.MemberStatus; 4 | import kr.dataportal.invitation.persistence.config.BaseEntity; 5 | 6 | import javax.persistence.Entity; 7 | import javax.persistence.EnumType; 8 | import javax.persistence.Enumerated; 9 | import javax.persistence.Table; 10 | 11 | /** 12 | * @author Heli 13 | * Created on 2022. 11. 30 14 | */ 15 | @Entity 16 | @Table(name = "member") 17 | public class MemberJpaEntity extends BaseEntity { 18 | 19 | private String name; 20 | private String phoneNumber; 21 | private String email; 22 | @Enumerated(EnumType.STRING) 23 | private MemberStatus status; 24 | 25 | protected MemberJpaEntity() { 26 | } 27 | 28 | private MemberJpaEntity(final String name, final String phoneNumber, final String email, final MemberStatus status) { 29 | this.name = name; 30 | this.phoneNumber = phoneNumber; 31 | this.email = email; 32 | this.status = status; 33 | } 34 | 35 | public static MemberJpaEntity newCandidate(final String name, final String phoneNumber, final String email) { 36 | return new MemberJpaEntity(name, phoneNumber, email, MemberStatus.CANDIDATE); 37 | } 38 | 39 | public MemberJpaEntity activate() { 40 | this.status = MemberStatus.ACTIVATE; 41 | return this; 42 | } 43 | 44 | public String getName() { 45 | return name; 46 | } 47 | 48 | public String getPhoneNumber() { 49 | return phoneNumber; 50 | } 51 | 52 | public String getEmail() { 53 | return email; 54 | } 55 | 56 | public MemberStatus getStatus() { 57 | return status; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-database/src/main/java/kr/dataportal/invitation/persistence/repository/member/MemberRepository.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence.repository.member; 2 | 3 | import kr.dataportal.invitation.persistence.entity.member.MemberJpaEntity; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | /** 7 | * @author Heli 8 | * Created on 2022. 11. 30 9 | */ 10 | public interface MemberRepository extends JpaRepository { 11 | } 12 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-database/src/main/java/kr/dataportal/invitation/persistence/service/member/MemberCommand.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence.service.member; 2 | 3 | import kr.dataportal.invitation.model.member.InviteMember; 4 | import kr.dataportal.invitation.persistence.entity.member.MemberJpaEntity; 5 | import kr.dataportal.invitation.persistence.repository.member.MemberRepository; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | /** 10 | * @author Heli 11 | * Created on 2022. 11. 30 12 | */ 13 | @Service 14 | @Transactional 15 | public class MemberCommand { 16 | private final MemberRepository memberRepository; 17 | 18 | public MemberCommand(final MemberRepository memberRepository) { 19 | this.memberRepository = memberRepository; 20 | } 21 | 22 | public MemberJpaEntity newCandidate(final InviteMember inviteMember) { 23 | // TODO 매번 Candidate를 만드는 것 보단 name + phoneNumber + email 조합으로 동일한 계정이 있는 경우 해당 계정을 초대하는 방향으로 잡는 것이 좋아보임 / getOrCreateCandidate 24 | MemberJpaEntity memberJpaEntity = MemberJpaEntity.newCandidate(inviteMember.name(), inviteMember.phoneNumber(), inviteMember.email()); 25 | return memberRepository.save(memberJpaEntity); 26 | } 27 | 28 | public MemberJpaEntity activate(final MemberJpaEntity entity) { 29 | return entity.activate(); 30 | } 31 | 32 | public MemberJpaEntity activate(final long memberId) { 33 | // TODO Exception 고도화 34 | MemberJpaEntity memberJpaEntity = memberRepository.findById(memberId).orElseThrow(); 35 | return activate(memberJpaEntity); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-database/src/main/java/kr/dataportal/invitation/persistence/service/member/MemberQuery.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence.service.member; 2 | 3 | import kr.dataportal.invitation.persistence.entity.member.MemberJpaEntity; 4 | import kr.dataportal.invitation.persistence.repository.member.MemberRepository; 5 | import kr.dataportal.invitation.persistence.service.member.exception.NotFoundMemberException; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | /** 10 | * @author Heli 11 | * Created on 2022. 11. 30 12 | */ 13 | @Service 14 | @Transactional(readOnly = true) 15 | public class MemberQuery { 16 | private final MemberRepository memberRepository; 17 | 18 | public MemberQuery(final MemberRepository memberRepository) { 19 | this.memberRepository = memberRepository; 20 | } 21 | 22 | public MemberJpaEntity findById(final long memberId) { 23 | return memberRepository.findById(memberId) 24 | .orElseThrow(() -> new NotFoundMemberException(memberId)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-database/src/main/java/kr/dataportal/invitation/persistence/service/member/exception/NotFoundMemberException.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence.service.member.exception; 2 | 3 | /** 4 | * @author Heli 5 | * Created on 2022. 11. 30 6 | */ 7 | public class NotFoundMemberException extends RuntimeException { 8 | 9 | private static final String MESSAGE_FORMAT = "can not found member [memberId=%s]"; 10 | 11 | public NotFoundMemberException(final long memberId) { 12 | super(String.format(MESSAGE_FORMAT, memberId)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-database/src/main/resources/application-persistence-database.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | jpa: 3 | open-in-view: false 4 | --- 5 | spring: 6 | config: 7 | activate: 8 | on-profile: local 9 | datasource: 10 | driverClassName: org.h2.Driver 11 | jpa: 12 | database: h2 13 | show-sql: true 14 | generate-ddl: true 15 | hibernate: 16 | ddl-auto: create 17 | properties: 18 | hibernate: 19 | format_sql: true 20 | 21 | logging: 22 | level: 23 | org.hibernate.SQL: DEBUG 24 | org.hibernate.type.descriptor.sql.BasicBinder: TRACE 25 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-database/src/test/java/kr/dataportal/invitation/persistence/service/member/MemberCommandTest.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence.service.member; 2 | 3 | import kr.dataportal.invitation.model.member.InviteMember; 4 | import kr.dataportal.invitation.model.member.MemberStatus; 5 | import kr.dataportal.invitation.persistence.entity.member.MemberJpaEntity; 6 | import kr.dataportal.invitation.persistence.repository.member.MemberRepository; 7 | import org.junit.jupiter.api.BeforeEach; 8 | import org.junit.jupiter.api.DisplayNameGeneration; 9 | import org.junit.jupiter.api.DisplayNameGenerator; 10 | import org.junit.jupiter.api.Test; 11 | import org.mockito.Mock; 12 | import org.mockito.MockitoAnnotations; 13 | 14 | import static org.assertj.core.api.AssertionsForClassTypes.assertThat; 15 | import static org.mockito.AdditionalAnswers.returnsFirstArg; 16 | import static org.mockito.ArgumentMatchers.any; 17 | import static org.mockito.Mockito.when; 18 | 19 | /** 20 | * @author Heli 21 | * Created on 2022. 11. 30 22 | */ 23 | @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) 24 | class MemberCommandTest { 25 | 26 | private final String name = "Heli"; 27 | private final String phoneNumber = "010-1111-2222"; 28 | private final String email = "heli@example.com"; 29 | private final InviteMember inviteMember = new InviteMember(name, phoneNumber, email); 30 | private final MemberJpaEntity candidateMemberJpaEntity = MemberJpaEntity.newCandidate(name, phoneNumber, email); 31 | private MemberCommand sut; 32 | @Mock 33 | private MemberRepository memberRepository; 34 | 35 | @BeforeEach 36 | void init() { 37 | MockitoAnnotations.openMocks(this); 38 | sut = new MemberCommand(memberRepository); 39 | } 40 | 41 | @Test 42 | void 후보_Member_엔티티를_생성할_수_있다() { 43 | when(memberRepository.save(any())).then(returnsFirstArg()); 44 | 45 | MemberJpaEntity actual = sut.newCandidate(inviteMember); 46 | 47 | assertThat(actual.getName()).isEqualTo(name); 48 | assertThat(actual.getPhoneNumber()).isEqualTo(phoneNumber); 49 | assertThat(actual.getEmail()).isEqualTo(email); 50 | assertThat(actual.getStatus()).isEqualTo(MemberStatus.CANDIDATE); 51 | } 52 | 53 | @Test 54 | void 후보_멤버를_활성화_할_수_있다() { 55 | MemberJpaEntity actual = sut.activate(candidateMemberJpaEntity); 56 | assertThat(actual.getName()).isEqualTo(name); 57 | assertThat(actual.getPhoneNumber()).isEqualTo(phoneNumber); 58 | assertThat(actual.getEmail()).isEqualTo(email); 59 | assertThat(actual.getStatus()).isEqualTo(MemberStatus.ACTIVATE); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-database/src/test/java/kr/dataportal/invitation/persistence/service/member/MemberQueryTest.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence.service.member; 2 | 3 | import kr.dataportal.invitation.model.member.MemberStatus; 4 | import kr.dataportal.invitation.persistence.entity.member.MemberJpaEntity; 5 | import kr.dataportal.invitation.persistence.repository.member.MemberRepository; 6 | import kr.dataportal.invitation.persistence.service.member.exception.NotFoundMemberException; 7 | import org.junit.jupiter.api.BeforeEach; 8 | import org.junit.jupiter.api.DisplayNameGeneration; 9 | import org.junit.jupiter.api.DisplayNameGenerator; 10 | import org.junit.jupiter.api.Test; 11 | import org.mockito.Mock; 12 | import org.mockito.MockitoAnnotations; 13 | 14 | import java.util.Optional; 15 | 16 | import static org.assertj.core.api.AssertionsForClassTypes.assertThat; 17 | import static org.junit.jupiter.api.Assertions.assertThrows; 18 | import static org.mockito.Mockito.when; 19 | 20 | /** 21 | * @author Heli 22 | * Created on 2022. 11. 30 23 | */ 24 | @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) 25 | class MemberQueryTest { 26 | 27 | private final MemberJpaEntity candidateMemberJpaEntity = MemberJpaEntity.newCandidate("Heli", "010-1111-2222", "heli@example.com"); 28 | @Mock 29 | private MemberRepository memberRepository; 30 | private MemberQuery sut; 31 | 32 | @BeforeEach 33 | void init() { 34 | MockitoAnnotations.openMocks(this); 35 | sut = new MemberQuery(memberRepository); 36 | } 37 | 38 | @Test 39 | void id_를_이용해_엔티티_조회_실패_시_NotFoundMemberException_예외_발생() { 40 | when(memberRepository.findById(1L)).thenReturn(Optional.empty()); 41 | 42 | assertThrows( 43 | NotFoundMemberException.class, 44 | () -> sut.findById(1L) 45 | ); 46 | } 47 | 48 | @Test 49 | void id_를_이용해_엔티티_조회_성공_시_엔티티_응답() { 50 | when(memberRepository.findById(1L)).thenReturn(Optional.of(candidateMemberJpaEntity)); 51 | 52 | MemberJpaEntity actual = sut.findById(1L); 53 | 54 | assertThat(actual.getName()).isEqualTo(actual.getName()); 55 | assertThat(actual.getPhoneNumber()).isEqualTo(actual.getPhoneNumber()); 56 | assertThat(actual.getEmail()).isEqualTo(actual.getEmail()); 57 | assertThat(actual.getStatus()).isEqualTo(MemberStatus.CANDIDATE); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-redis-adapter/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'org.springframework.boot:spring-boot-starter-data-redis' 3 | 4 | // https://mvnrepository.com/artifact/it.ozimov/embedded-redis 5 | implementation 'it.ozimov:embedded-redis:0.7.3' 6 | 7 | // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind 8 | implementation 'com.fasterxml.jackson.core:jackson-databind:2.14.1' 9 | } 10 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-redis-adapter/src/main/java/kr/dataportal/invitation/persistence/config/LocalRedisConfig.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.context.annotation.Profile; 5 | import redis.embedded.RedisServer; 6 | 7 | import javax.annotation.PostConstruct; 8 | import javax.annotation.PreDestroy; 9 | 10 | /** 11 | * @author Heli 12 | * Created on 2022. 11. 30 13 | */ 14 | @Profile({"local"}) 15 | @Configuration 16 | public class LocalRedisConfig { 17 | 18 | private final RedisServer redisServer = new RedisServer(); 19 | 20 | @PostConstruct 21 | public void initRedis() { 22 | try { 23 | redisServer.start(); 24 | } catch (Exception e) { 25 | // TODO logging 26 | } 27 | } 28 | 29 | @PreDestroy 30 | public void destroyRedis() { 31 | try { 32 | redisServer.stop(); 33 | } catch (Exception e) { 34 | // TODO logging 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-redis-adapter/src/main/java/kr/dataportal/invitation/persistence/service/LettuceRedisService.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence.service; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.springframework.data.redis.core.StringRedisTemplate; 5 | import org.springframework.stereotype.Service; 6 | 7 | import java.time.Duration; 8 | import java.util.Optional; 9 | 10 | /** 11 | * @author Heli 12 | * Created on 2022. 11. 30 13 | */ 14 | @Service 15 | public class LettuceRedisService implements RedisService { 16 | 17 | private static final String KEY_PREFIX = "dataportal.kr_invitaion:"; 18 | 19 | private final StringRedisTemplate redisTemplate; 20 | private final ObjectMapper objectMapper; 21 | 22 | public LettuceRedisService(final StringRedisTemplate redisTemplate, final ObjectMapper objectMapper) { 23 | this.redisTemplate = redisTemplate; 24 | this.objectMapper = objectMapper; 25 | } 26 | 27 | @Override 28 | public Optional get(final String key, final Class type) { 29 | String serializedValue = redisTemplate.opsForValue().get(redisKey(key)); 30 | try { 31 | return Optional.of(objectMapper.readValue(serializedValue, type)); 32 | } catch (Exception e) { 33 | // TODO logging 34 | } 35 | return Optional.empty(); 36 | } 37 | 38 | @Override 39 | public void set(final String key, final Object value, final Duration duration) { 40 | try { 41 | String serializedValue = objectMapper.writeValueAsString(value); 42 | redisTemplate.opsForValue().set(redisKey(key), serializedValue, duration); 43 | } catch (Exception e) { 44 | // TODO logging 45 | } 46 | } 47 | 48 | @Override 49 | public boolean setIfAbsent(final String key, final Object value, final Duration duration) { 50 | try { 51 | String serializedValue = objectMapper.writeValueAsString(value); 52 | return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(redisKey(key), serializedValue, duration)); 53 | } catch (Exception e) { 54 | // TODO logging 55 | } 56 | return false; 57 | } 58 | 59 | @Override 60 | public boolean delete(final String key) { 61 | return Boolean.TRUE.equals(redisTemplate.delete(redisKey(key))); 62 | } 63 | 64 | private String redisKey(final String key) { 65 | return KEY_PREFIX + key; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-redis-adapter/src/main/java/kr/dataportal/invitation/persistence/service/RedisService.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.persistence.service; 2 | 3 | import java.time.Duration; 4 | import java.util.Optional; 5 | 6 | /** 7 | * @author Heli 8 | * Created on 2022. 11. 30 9 | */ 10 | public interface RedisService { 11 | Optional get(final String key, final Class type); 12 | 13 | void set(final String key, final Object value, final Duration duration); 14 | 15 | boolean setIfAbsent(final String key, final Object value, final Duration duration); 16 | 17 | boolean delete(final String key); 18 | } 19 | -------------------------------------------------------------------------------- /member-invitation-infrastructure/persistence-redis-adapter/src/main/resources/application-persistence-redis-adapter.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | redis: 3 | lettuce: 4 | pool: 5 | max-wait: 1000ms 6 | timeout: 1000ms 7 | host: localhost 8 | port: 6379 9 | -------------------------------------------------------------------------------- /member-invitation-interface/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation project(':member-invitation-domain') 3 | implementation project(':commons:common-model') 4 | implementation project(':commons:common-util') 5 | 6 | implementation 'org.springframework.boot:spring-boot-starter-web' 7 | implementation 'org.springframework.boot:spring-boot-starter-aop' 8 | implementation 'org.springframework.boot:spring-boot-starter-validation' 9 | } 10 | -------------------------------------------------------------------------------- /member-invitation-interface/src/main/java/kr/dataportal/invitation/MemberInvitationApplication.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class MemberInvitationApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(MemberInvitationApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /member-invitation-interface/src/main/java/kr/dataportal/invitation/api/invitation/InvitationRestController.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.api.invitation; 2 | 3 | import kr.dataportal.invitation.api.invitation.dto.InvitationResponseDto; 4 | import kr.dataportal.invitation.api.invitation.dto.InviteWorkspaceRequestDto; 5 | import kr.dataportal.invitation.api.invitation.mapper.InvitationMapper; 6 | import kr.dataportal.invitation.invitation.domain.Invitation; 7 | import kr.dataportal.invitation.invitation.usecase.AcceptInvitationUseCase; 8 | import kr.dataportal.invitation.invitation.usecase.InviteWorkspaceUseCase; 9 | import kr.dataportal.invitation.invitation.usecase.QueryInvitationByCodeUseCase; 10 | import kr.dataportal.invitation.model.member.InviteMember; 11 | import org.springframework.validation.annotation.Validated; 12 | import org.springframework.web.bind.annotation.*; 13 | 14 | /** 15 | * @author Heli 16 | * Created on 2022. 11. 30 17 | */ 18 | @RestController 19 | public class InvitationRestController { 20 | 21 | private final InviteWorkspaceUseCase inviteWorkspaceUseCase; 22 | private final QueryInvitationByCodeUseCase queryInvitationByCodeUseCase; 23 | private final AcceptInvitationUseCase acceptInvitationUseCase; 24 | 25 | public InvitationRestController(final InviteWorkspaceUseCase inviteWorkspaceUseCase, final QueryInvitationByCodeUseCase queryInvitationByCodeUseCase, final AcceptInvitationUseCase acceptInvitationUseCase) { 26 | this.inviteWorkspaceUseCase = inviteWorkspaceUseCase; 27 | this.queryInvitationByCodeUseCase = queryInvitationByCodeUseCase; 28 | this.acceptInvitationUseCase = acceptInvitationUseCase; 29 | } 30 | 31 | @PostMapping("/api/v1/workspace/{workspaceId}/invitation") 32 | public InvitationResponseDto inviteWorkspace( 33 | @PathVariable final long workspaceId, 34 | @RequestBody @Validated final InviteWorkspaceRequestDto dto 35 | ) { 36 | Invitation invitation = inviteWorkspaceUseCase.command(new InviteWorkspaceUseCase.Command( 37 | workspaceId, 38 | new InviteMember(dto.inviteMemberName(), dto.inviteMemberPhoneNumber(), dto.inviteMemberEmail()) 39 | )); 40 | 41 | return InvitationMapper.toResponseDto(invitation); 42 | } 43 | 44 | @GetMapping("/api/v1/invitation/{code}") 45 | public InvitationResponseDto invitation( 46 | @PathVariable final String code 47 | ) { 48 | Invitation invitation = queryInvitationByCodeUseCase.query(new QueryInvitationByCodeUseCase.Query(code)); 49 | 50 | return InvitationMapper.toResponseDto(invitation); 51 | } 52 | 53 | @PostMapping("/api/v1/invitation/{code}/accept") 54 | public InvitationResponseDto acceptInvitation( 55 | @PathVariable final String code 56 | ) { 57 | Invitation invitation = acceptInvitationUseCase.command(new AcceptInvitationUseCase.Command(code)); 58 | 59 | return InvitationMapper.toResponseDto(invitation); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /member-invitation-interface/src/main/java/kr/dataportal/invitation/api/invitation/dto/InvitationResponseDto.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.api.invitation.dto; 2 | 3 | /** 4 | * @author Heli 5 | * Created on 2022. 11. 30 6 | */ 7 | public record InvitationResponseDto( 8 | long workspaceId, 9 | long memberId, 10 | long expiresAt, 11 | String code 12 | ) { 13 | } 14 | -------------------------------------------------------------------------------- /member-invitation-interface/src/main/java/kr/dataportal/invitation/api/invitation/dto/InviteWorkspaceRequestDto.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.api.invitation.dto; 2 | 3 | import javax.validation.constraints.Email; 4 | import javax.validation.constraints.NotEmpty; 5 | 6 | /** 7 | * @author Heli 8 | * Created on 2022. 11. 30 9 | */ 10 | public record InviteWorkspaceRequestDto( 11 | @NotEmpty 12 | String inviteMemberName, 13 | @NotEmpty 14 | String inviteMemberPhoneNumber, 15 | @Email 16 | String inviteMemberEmail 17 | ) { 18 | } 19 | -------------------------------------------------------------------------------- /member-invitation-interface/src/main/java/kr/dataportal/invitation/api/invitation/mapper/InvitationMapper.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.api.invitation.mapper; 2 | 3 | import kr.dataportal.invitation.api.invitation.dto.InvitationResponseDto; 4 | import kr.dataportal.invitation.invitation.domain.Invitation; 5 | import kr.dataportal.invitation.util.DateTimeUtils; 6 | 7 | /** 8 | * @author Heli 9 | * Created on 2022. 11. 30 10 | */ 11 | public class InvitationMapper { 12 | 13 | public static InvitationResponseDto toResponseDto(final Invitation invitation) { 14 | return new InvitationResponseDto( 15 | invitation.target().workspaceId(), 16 | invitation.target().memberId(), 17 | DateTimeUtils.toEpochMillis(invitation.expiresAt()), 18 | invitation.code() 19 | ); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /member-invitation-interface/src/main/java/kr/dataportal/invitation/api/member/MemberRestController.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.api.member; 2 | 3 | import kr.dataportal.invitation.api.member.dto.MemberResponseDto; 4 | import kr.dataportal.invitation.api.member.mapper.MemberMapper; 5 | import kr.dataportal.invitation.member.domain.Member; 6 | import kr.dataportal.invitation.member.usecase.QueryMemberByIdUseCase; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.PathVariable; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | /** 12 | * @author Heli 13 | * Created on 2022. 11. 30 14 | */ 15 | @RestController 16 | public class MemberRestController { 17 | 18 | private final QueryMemberByIdUseCase queryMemberByIdUseCase; 19 | 20 | public MemberRestController(final QueryMemberByIdUseCase queryMemberByIdUseCase) { 21 | this.queryMemberByIdUseCase = queryMemberByIdUseCase; 22 | } 23 | 24 | @GetMapping("/api/v1/member/{memberId}") 25 | public MemberResponseDto member( 26 | @PathVariable final long memberId 27 | ) { 28 | Member member = queryMemberByIdUseCase.query(new QueryMemberByIdUseCase.Query( 29 | memberId 30 | )); 31 | 32 | return MemberMapper.toResponseDto(member); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /member-invitation-interface/src/main/java/kr/dataportal/invitation/api/member/dto/MemberResponseDto.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.api.member.dto; 2 | 3 | /** 4 | * @author Heli 5 | * Created on 2022. 11. 30 6 | */ 7 | public record MemberResponseDto( 8 | long id, 9 | long createdAt, 10 | long lastModifiedAt, 11 | String name, 12 | String phoneNumber, 13 | String email, 14 | String status 15 | ) { 16 | } 17 | -------------------------------------------------------------------------------- /member-invitation-interface/src/main/java/kr/dataportal/invitation/api/member/mapper/MemberMapper.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.api.member.mapper; 2 | 3 | import kr.dataportal.invitation.api.member.dto.MemberResponseDto; 4 | import kr.dataportal.invitation.member.domain.Member; 5 | import kr.dataportal.invitation.util.DateTimeUtils; 6 | 7 | /** 8 | * @author Heli 9 | * Created on 2022. 11. 30 10 | */ 11 | public class MemberMapper { 12 | 13 | public static MemberResponseDto toResponseDto(final Member member) { 14 | return new MemberResponseDto( 15 | member.id(), 16 | DateTimeUtils.toEpochMillis(member.createdAt()), 17 | DateTimeUtils.toEpochMillis(member.lastModifiedAt()), 18 | member.name(), 19 | member.phoneNumber(), 20 | member.email(), 21 | member.status().name() 22 | ); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /member-invitation-interface/src/main/java/kr/dataportal/invitation/config/ErrorResponseDto.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.config; 2 | 3 | import org.springframework.http.HttpStatus; 4 | 5 | /** 6 | * @author Heli 7 | * Created on 2022. 11. 30 8 | */ 9 | public record ErrorResponseDto( 10 | String code, 11 | String message 12 | ) { 13 | 14 | public static final ErrorResponseDto BAD_REQUEST = toErrorResponseDto(HttpStatus.BAD_REQUEST); 15 | public static final ErrorResponseDto FORBIDDEN = toErrorResponseDto(HttpStatus.FORBIDDEN); 16 | public static final ErrorResponseDto NOT_FOUND = toErrorResponseDto(HttpStatus.NOT_FOUND); 17 | public static final ErrorResponseDto INTERNAL_SERVER_ERROR = toErrorResponseDto(HttpStatus.INTERNAL_SERVER_ERROR); 18 | 19 | 20 | private static ErrorResponseDto toErrorResponseDto(final HttpStatus httpStatus) { 21 | return new ErrorResponseDto(httpStatus.name(), httpStatus.getReasonPhrase()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /member-invitation-interface/src/main/java/kr/dataportal/invitation/config/aop/ApiRestControllerAdvice.java: -------------------------------------------------------------------------------- 1 | package kr.dataportal.invitation.config.aop; 2 | 3 | import kr.dataportal.invitation.config.ErrorResponseDto; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.web.bind.MethodArgumentNotValidException; 6 | import org.springframework.web.bind.annotation.ExceptionHandler; 7 | import org.springframework.web.bind.annotation.ResponseStatus; 8 | import org.springframework.web.bind.annotation.RestControllerAdvice; 9 | import org.springframework.web.servlet.NoHandlerFoundException; 10 | 11 | import javax.validation.ConstraintViolationException; 12 | 13 | /** 14 | * @author Heli 15 | * Created on 2022. 11. 30 16 | */ 17 | @RestControllerAdvice 18 | public class ApiRestControllerAdvice { 19 | 20 | /** 21 | * 400 22 | */ 23 | @ResponseStatus(HttpStatus.BAD_REQUEST) 24 | @ExceptionHandler(ConstraintViolationException.class) 25 | ErrorResponseDto handleException(ConstraintViolationException e) { 26 | // TODO logging 27 | return ErrorResponseDto.BAD_REQUEST; 28 | } 29 | 30 | /** 31 | * 400 32 | */ 33 | @ResponseStatus(HttpStatus.BAD_REQUEST) 34 | @ExceptionHandler(MethodArgumentNotValidException.class) 35 | ErrorResponseDto handleException(MethodArgumentNotValidException e) { 36 | // TODO logging 37 | return ErrorResponseDto.BAD_REQUEST; 38 | } 39 | 40 | /* 41 | * 403 42 | */ 43 | // TODO Authorization Exception Handling 44 | 45 | /** 46 | * 404 47 | */ 48 | @ResponseStatus(HttpStatus.NOT_FOUND) 49 | @ExceptionHandler(NoHandlerFoundException.class) 50 | ErrorResponseDto handleException(NoHandlerFoundException e) { 51 | // TODO logging 52 | return ErrorResponseDto.NOT_FOUND; 53 | } 54 | 55 | /** 56 | * 500 57 | */ 58 | @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 59 | @ExceptionHandler(Exception.class) 60 | ErrorResponseDto handleException(Exception e) { 61 | // TODO logging 62 | return ErrorResponseDto.INTERNAL_SERVER_ERROR; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /member-invitation-interface/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: member-invitation 4 | profiles: 5 | include: 6 | - persistence-database 7 | - persistence-redis-adapter 8 | -------------------------------------------------------------------------------- /member-invitation-interface/src/test/resources/http/invitation.http: -------------------------------------------------------------------------------- 1 | ### workspace에 대한 초대장 발급 - 성공 2 | POST http://localhost:8080/api/v1/workspace/1/invitation 3 | Content-Type: application/json 4 | 5 | { 6 | "inviteMemberName": "Heli", 7 | "inviteMemberPhoneNumber": "010-1111-2222", 8 | "inviteMemberEmail": "heli@example.com" 9 | } 10 | 11 | ### workspace에 대한 초대장 발급 - 실패 (BAD_REQUEST) 12 | POST http://localhost:8080/api/v1/workspace/1/invitation 13 | Content-Type: application/json 14 | 15 | { 16 | "inviteMemberName": "", 17 | "inviteMemberPhoneNumber": "010-1111-2222", 18 | "inviteMemberEmail": "heli@example.com" 19 | } 20 | 21 | ### 발급된 초대장 조회 22 | GET http://localhost:8080/api/v1/invitation/F7v93E42wpfR60wmlTVFGbBYDzI6RgMc 23 | 24 | ### 기존에 가입된 Member 조회 25 | GET http://localhost:8080/api/v1/member/1 26 | 27 | ### 초대 승낙 28 | POST http://localhost:8080/api/v1/invitation/F7v93E42wpfR60wmlTVFGbBYDzI6RgMc/accept 29 | Content-Type: application/json 30 | 31 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'member-invitation-java-springboot' 2 | include 'commons' 3 | include 'commons:common-model' 4 | include 'member-invitation-domain' 5 | include 'member-invitation-interface' 6 | include 'member-invitation-infrastructure' 7 | include 'member-invitation-infrastructure:persistence-database' 8 | include 'member-invitation-infrastructure:persistence-redis-adapter' 9 | include 'commons:common-util' 10 | 11 | --------------------------------------------------------------------------------