Skip to content

Commit

Permalink
Merge pull request #231 from haedoang/feature/room-with-user
Browse files Browse the repository at this point in the history
[feature/room-with-user] room api 작성
  • Loading branch information
haedoang authored Oct 11, 2023
2 parents 25d7507 + 563ce2f commit 3006f93
Show file tree
Hide file tree
Showing 12 changed files with 122 additions and 32 deletions.
17 changes: 8 additions & 9 deletions src/main/java/com/koliving/api/KolivingApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,18 +81,17 @@ CommandLineRunner commandLineRunner(
initFurnishings(furnishingRepository);
initLocations(locationRepository);
initLanguages(languageRepository);
//FIXME 테스트 후 제거 예정
initRooms(roomRepository, locationRepository, furnishingRepository, imageFileRepository);
initUser(userRepository, encoder);
User user = initUser(userRepository, encoder);
initRooms(roomRepository, locationRepository, furnishingRepository, imageFileRepository, user);
};
}

private void initUser(UserRepository userRepository, PasswordEncoder encoder) {
private User initUser(UserRepository userRepository, PasswordEncoder encoder) {
final User user = User.builder()
.email("[email protected]")
.build();
user.setPassword(encoder.encode("test1234!@"));
userRepository.save(user);
return userRepository.save(user);
}

private void initImageFiles(ImageFileRepository imageFileRepository) {
Expand All @@ -105,7 +104,7 @@ private void initImageFiles(ImageFileRepository imageFileRepository) {
}

private void initRooms(RoomRepository roomRepository, LocationRepository locationRepository,
FurnishingRepository furnishingRepository, ImageFileRepository imageFileRepository) {
FurnishingRepository furnishingRepository, ImageFileRepository imageFileRepository, User user) {
Location location = locationRepository.findByName("Songjeong").get();
Location location2 = locationRepository.findByName("Huam").get();
Location location3 = locationRepository.findByName("Amsaje 1").get();
Expand Down Expand Up @@ -137,7 +136,7 @@ private void initRooms(RoomRepository roomRepository, LocationRepository locatio
imageFile,
imageFile2
)
),
).by(user),
Room.valueOf(
location2,
RoomInfo.valueOf(RoomType.ONE_BED_FLATS, 1, 2, 2),
Expand All @@ -148,7 +147,7 @@ private void initRooms(RoomRepository roomRepository, LocationRepository locatio
LocalDate.of(2023, 8, 30),
"용산구 후암동) ONE_BED_FLATS, 방1, 욕실2, 룸메2 보증금 5_000_000 월세X 관리비X 가구X 2023.08.30 입주",
Sets.newHashSet()
),
).by(user),
Room.valueOf(
location3,
RoomInfo.valueOf(RoomType.ONE_BED_FLATS, 1, 2, 2),
Expand All @@ -159,7 +158,7 @@ private void initRooms(RoomRepository roomRepository, LocationRepository locatio
LocalDate.now(),
"강동구 암사제1동) ONE_BED_FLATS, 방1, 욕실2, 룸메2 보증금 5_000_000 월세300_000 관리비X 가구X 2023.08.30 입주",
Sets.newHashSet()
)
).by(user)
)
);

Expand Down
3 changes: 1 addition & 2 deletions src/main/java/com/koliving/api/auth/AuthFacade.java
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,8 @@ public TokenResponse createToken(TokenRequest request) {
.orElseThrow(() -> new KolivingServiceException(UNAUTHORIZED));
user.checkPassword(passwordEncoder.encode(request.password()));

//TODO refresh 토큰 존재 확인
final JwtTokenDto jwtTokenDto = issueAuthTokens(user);

return TokenResponse.valueOf(jwtTokenDto.getAccessToken());
return TokenResponse.valueOf(jwtTokenDto.getAccessToken(), jwtTokenDto.getRefreshToken());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public record TokenRequest(
@Schema(description = "계정", example = "[email protected]")
@NotEmpty String email,

@Schema(description = "비밀번호", example = "password1234")
@Schema(description = "비밀번호", example = "test1234!@")
@NotEmpty String password
) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@
*/
@Schema(description = "토큰 발급 정보")
public record TokenResponse(
@Schema(description = "액세스 토큰", example = "eyJhbGciOiJIUzM4NCJ9.eyJzdWIiOiI0IiwiYXV0aG9yaXRpZXMiOlt7ImF1dGhvcml0eSI6Im1lbWJlcjp3cml0ZSJ9LHsiYXV0aG9yaXR5IjoibWVtYmVyOnJlYWQifSx7ImF1dGhvcml0eSI6InJvb206cmVhZCJ9LHsiYXV0aG9yaXR5Ijoicm9vbTp3cml0ZSJ9LHsiYXV0aG9yaXR5IjoiUk9MRV9BRE1JTiJ9XSwiaWF0IjoxNjU4MjE4MTI2LCJleHAiOjE2ODk2OTI0MDB9.9S32yrsYqbnLQZGP4kPnoK3K5M1o2RmTzF-rbj8ABqFCk95tB-8irPCArdptIUp_")
String accessToken
@Schema(description = "Access 토큰", example = "eyJhbGciOiJIUzM4NCJ9.eyJzdWIiOiI0IiwiYXV0aG9yaXRpZXMiOlt7ImF1dGhvcml0eSI6Im1lbWJlcjp3cml0ZSJ9LHsiYXV0aG9yaXR5IjoibWVtYmVyOnJlYWQifSx7ImF1dGhvcml0eSI6InJvb206cmVhZCJ9LHsiYXV0aG9yaXR5Ijoicm9vbTp3cml0ZSJ9LHsiYXV0aG9yaXR5IjoiUk9MRV9BRE1JTiJ9XSwiaWF0IjoxNjU4MjE4MTI2LCJleHAiOjE2ODk2OTI0MDB9.9S32yrsYqbnLQZGP4kPnoK3K5M1o2RmTzF-rbj8ABqFCk95tB-8irPCArdptIUp_")
String accessToken,

@Schema(description = "Refresh 토큰", example = "eyJhbGciOiJIUzM4NCJ9.eyJzdWIiOiI0IiwiYXV0aG9yaXRpZXMiOlt7ImF1dGhvcml0eSI6Im1lbWJlcjp3cml0ZSJ9LHsiYXV0aG9yaXR5IjoibWVtYmVyOnJlYWQifSx7ImF1dGhvcml0eSI6InJvb206cmVhZCJ9LHsiYXV0aG9yaXR5Ijoicm9vbTp3cml0ZSJ9LHsiYXV0aG9yaXR5IjoiUk9MRV9BRE1JTiJ9XSwiaWF0IjoxNjU4MjE4MTI2LCJleHAiOjE2ODk2OTI0MDB9.9S32yrsYqbnLQZGP4kPnoK3K5M1o2RmTzF-rbj8ABqFCk95tB-8irPCArdptIUp_")
String refreshToken
) {

public static TokenResponse valueOf(String accessToken) {
return new TokenResponse(accessToken);
public static TokenResponse valueOf(String accessToken, String refreshToken) {
return new TokenResponse(accessToken, refreshToken);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
Expand Down Expand Up @@ -33,5 +34,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
httpUtils.getCookieOfAccessToken(accessToken),
httpUtils.getCookieOfRefreshToken(refreshToken)
);

response.addHeader(HttpHeaders.AUTHORIZATION, "bearer " + accessToken);
}
}
13 changes: 9 additions & 4 deletions src/main/java/com/koliving/api/room/application/RoomService.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@
import com.koliving.api.room.application.dto.RoomSaveRequest;
import com.koliving.api.room.application.dto.RoomSearchCondition;
import com.koliving.api.room.domain.Furnishing;
import com.koliving.api.room.domain.QRoom;
import com.koliving.api.room.domain.Room;
import com.koliving.api.room.infra.FurnishingRepository;
import com.koliving.api.room.infra.RoomRepository;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.koliving.api.user.User;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -50,12 +50,12 @@ public List<RoomResponse> list() {
}

@Transactional
public Long save(RoomSaveRequest request) {
public Long save(RoomSaveRequest request, User user) {
Room room = request.toEntity(
getLocationById(request.locationId()),
getFurnishingsByIds(request.furnishingIds()),
getImageFiles(request.imageIds())
);
).by(user);
final Room savedRoom = roomRepository.save(room);

return savedRoom.getId();
Expand Down Expand Up @@ -98,4 +98,9 @@ private Location getLocationById(Long locationId) {
public Page<Room> search(Pageable pageable, RoomSearchCondition condition) {
return roomRepository.search(pageable, condition);
}

public Room findOne(Long id) {
return roomRepository.findByIdWithUser(id)
.orElseThrow(() -> new KolivingServiceException(RECORD_NOT_EXIST));
}
}
28 changes: 21 additions & 7 deletions src/main/java/com/koliving/api/room/domain/Room.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package com.koliving.api.room.domain;

import com.koliving.api.base.domain.BaseEntity;
import com.koliving.api.base.exception.KolivingServiceException;
import com.koliving.api.file.domain.ImageFile;
import com.koliving.api.location.domain.Location;
import com.koliving.api.room.domain.info.RoomInfo;
import com.koliving.api.user.User;
import jakarta.persistence.AttributeOverride;
import jakarta.persistence.Column;
import jakarta.persistence.Embedded;
Expand All @@ -25,8 +27,10 @@

import java.time.LocalDate;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

import static com.koliving.api.base.ServiceError.ILLEGAL_ROOM_INFO;
import static jakarta.persistence.GenerationType.IDENTITY;
import static lombok.AccessLevel.PROTECTED;

Expand All @@ -50,7 +54,11 @@ public class Room extends BaseEntity {
private Long id;

@OneToOne
@JoinColumn(name = "location_id")
@JoinColumn(name = "user_id", nullable = false)
private User user;

@OneToOne
@JoinColumn(name = "location_id", nullable = false)
private Location location;

@Embedded
Expand Down Expand Up @@ -81,7 +89,7 @@ public class Room extends BaseEntity {
@Lob
private String description;

@OneToMany
@ManyToMany
@JoinTable(
name = "TB_ROOM_IMAGES",
joinColumns = @JoinColumn(name = "room_id"),
Expand All @@ -102,10 +110,6 @@ private Room(Location location, RoomInfo roomInfo, Money deposit, Money monthlyR
this.imageFiles = imageFiles;
}

private void validate(Money deposit, Money monthlyRent, Set<ImageFile> imageFiles) {
//TODO 최대값 validation 추가
}

public static Room valueOf(
Location location,
RoomInfo info,
Expand All @@ -120,6 +124,16 @@ public static Room valueOf(
return new Room(location, info, deposit, monthlyRent, maintenance, furnishings, availableDate, description, imageFiles);
}

private Long userId;
private void validate(Money deposit, Money monthlyRent, Set<ImageFile> imageFiles) {
//TODO 최대값 validation 추가
}

public Room by(User user) {
if (Objects.isNull(user)) {
throw new KolivingServiceException(ILLEGAL_ROOM_INFO);
}

this.user = user;
return this;
}
}
10 changes: 10 additions & 0 deletions src/main/java/com/koliving/api/room/infra/RoomRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,17 @@

import com.koliving.api.room.domain.Room;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;
import java.util.Optional;

public interface RoomRepository extends JpaRepository<Room, Long>, RoomRepositoryQueryDsl {

@Query("select r from TB_ROOM r join fetch r.user u")
List<Room> findAllWithUser();

@Query("select r from TB_ROOM r join fetch r.user u where r.id=:id")
Optional<Room> findByIdWithUser(Long id);

}
29 changes: 27 additions & 2 deletions src/main/java/com/koliving/api/room/ui/RoomController.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.koliving.api.room.application.dto.RoomSaveRequest;
import com.koliving.api.room.application.dto.RoomSearchCondition;
import com.koliving.api.room.domain.Room;
import com.koliving.api.user.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
Expand All @@ -15,12 +16,16 @@
import java.util.List;

import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
Expand Down Expand Up @@ -49,8 +54,8 @@ public class RoomController {
),
})
@PostMapping
public ResponseEntity<Long> save(@RequestBody RoomSaveRequest request) {
final Long id = roomService.save(request);
public ResponseEntity<Long> save(@RequestBody RoomSaveRequest request, @AuthenticationPrincipal User user) {
final Long id = roomService.save(request, user);

return ResponseEntity.created(URI.create("api/v1/rooms/" + id))
.build();
Expand All @@ -75,4 +80,24 @@ public ResponseEntity<Page<Room>> search(@ParameterObject @PageableDefault Pagea
return ResponseEntity.ok()
.body(roomService.search(pageable, condition));
}

@Operation(
summary = "방 조회",
description = "방을 조회합니다.",
responses = {
@ApiResponse(
responseCode = "200",
description = "방 조회 성공"
),
@ApiResponse(
responseCode = "400",
description = "방 조회 실패",
content = @Content(schema = @Schema(implementation = ErrorResponse.class))
),
})
@GetMapping("/{id}")
public ResponseEntity<Room> findById(@PathVariable Long id) {
return ResponseEntity.ok()
.body(roomService.findOne(id));
}
}
4 changes: 3 additions & 1 deletion src/main/java/com/koliving/api/user/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ public class User implements UserDetails {

private String description;

@Column
private String imageUrl;

@Enumerated(EnumType.STRING)
@Column(name = "USER_ROLE")
private UserRole userRole;
Expand Down Expand Up @@ -139,5 +142,4 @@ public boolean isCredentialsNonExpired() {
public boolean checkPassword(String password) {
return this.password.equals(password);
}

}
14 changes: 14 additions & 0 deletions src/test/java/com/koliving/api/fixtures/UserFixture.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.koliving.api.fixtures;

import com.koliving.api.user.User;

import java.util.UUID;

public class UserFixture {
public static User createUser() {
User user = User.builder()
.email(String.format("%[email protected]", UUID.randomUUID())).build();

return user;
}
}
Loading

0 comments on commit 3006f93

Please sign in to comment.