Skip to content

Commit

Permalink
Merge pull request #36 from 2E1I/dev
Browse files Browse the repository at this point in the history
friends, 유저 관련 api 개발 완료
  • Loading branch information
CEO-Nick authored May 16, 2024
2 parents 90da994 + f3e39e9 commit 617f999
Show file tree
Hide file tree
Showing 22 changed files with 315 additions and 90 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,17 @@ public class NicknameConst {
);

public static final List<String> NOUNS = Arrays.asList(
"사과", "바나나", "커피", "책", "차", "고양이", "개", "꽃", "정원", "집",
"섬", "주스", "키스", "나무", "달", "산", "새", "바다", "태양", "교통",
"우산", "마을", "벽", "소", "시계", "노트북", "사진", "카메라", "라디오", "텔레비전",
"핸드폰", "냉장고", "의자", "책상", "문", "창문", "시계", "램프", "거울", "그림",
"침대", "담요", "이불", "베개", "소파", "커튼", "브러시", "병", "컵", "접시",
"식탁", "커트러리", "나이프", "포크", "스푼", "전자레인지", "오븐", "요리", "음악", "노래",
"춤", "영화", "비디오", "게임", "파티", "휴일", "선물", "카드", "편지", "책장",
"화분", "식물", "색깔", "도구", "망치", "못", "조각", "패턴", "디자인", "모양",
"크기", "무게", "공원", "길", "다리", "강", "숲", "계절", "여름", "가을",
"겨울", "봄", "행복", "사랑", "기쁨", "슬픔", "분노", "두려움", "기대", "실망",
"호기심", "평화", "전쟁", "뉴스", "신문", "잡지", "보고서", "이메일", "인터넷", "웹사이트",
"프로그램", "소프트웨어", "하드웨어", "네트워크", "데이터"
"호랑이", "사자", "기린", "코끼리", "하마", "코뿔소", "얼룩말", "늑대", "여우", "곰",
"판다", "북극곰", "사슴", "갈매기", "앵무새", "백조", "펭귄", "돌고래", "상어", "고래",
"뱀", "도마뱀", "악어", "거북", "이구아나", "개구리", "두꺼비", "매", "독수리", "부엉이",
"고양이", "개", "햄스터", "기니피그", "토끼", "비버", "다람쥐", "너구리", "족제비", "몽구스",
"침팬지", "오랑우탄", "고릴라", "원숭이", "마멋", "청설모", "스컹크", "수달", "하이에나", "아르마딜로",
"캥거루", "코알라", "타조", "에뮤", "알파카", "라마", "플라밍고", "악어새", "바다표범", "해마",
"큰바다거북", "칠면조", "오리", "거위", "백로", "황새", "공작", "비둘기", "까치", "앵무새",
"설치류", "미어캣", "코요테", "울버린", "수달", "멧돼지", "호저", "마코호크", "콘도르", "박쥐",
"청개구리", "이리", "바다사자", "미어캣", "와토가이", "필베", "누", "흰머리독수리", "황금독수리", "가젤",
"영양", "바비루사", "노새", "올빼미", "바실리스크", "모래뱀", "보아뱀", "갈라파고스거북", "점박이물범", "포로투칸",
"알바트로스", "오코피", "바다코끼리", "타프", "림프", "마자람"
);

public static final int WORD_NUM = NOUNS.size();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.e2i1.linkeepserver.common.constant;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PageConst {
public static final String DEFAULT_PAGE_SIZE = "10";

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public enum ErrorCode{

// 유저 관련 에러 코드
USER_NOT_FOUND(34040,HttpStatus.NOT_FOUND, "사용자를 찾을 수 없음"),
NICKNAME_DUPLICATED(34000,HttpStatus.BAD_REQUEST, "닉네임이 중복됩니다."),

// 모음집 관련 에러 코드
COLLECTION_NOT_FOUND(44040,HttpStatus.NOT_FOUND, "모음집을 찾을 수 없음"),
Expand All @@ -47,6 +48,8 @@ public enum ErrorCode{
RETRY_EXCEEDED(85000, HttpStatus.INTERNAL_SERVER_ERROR, "랜덤 닉네임 생성 재시도 횟수를 초과했습니다."),


//좋아요 관련 에러 코드
LIKE_NOT_FOUND(94040,HttpStatus.NOT_FOUND,"사용자가 모음집을 좋아요한 기록이 없습니다.")

;
private final int errorCode;
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/e2i1/linkeepserver/config/WebConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ public class WebConfig implements WebMvcConfigurer {
"/",
"favicon.ico",
"/error",
"/api/users/login"
"/api/users/login",
"/api/users/register"
);

private final List<String> SWAGGER = List.of(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,20 @@ public List<CollectionTitleResDTO> getTitle(UsersEntity user){
}

@Transactional
public Long updateNumOfLikes(Long collectionId,UsersEntity user){
public Long updateNumOfLikes(Long collectionId,UsersEntity user, boolean isFlag){
CollectionsEntity collection = collectionsService.findByIdWithThrow(collectionId);
LikeOthersEntity likeOther = likeOthersConverter.toLikeOthersEntity(collection,user);
likeOthersService.updateLike(likeOther);
collection.updateLikes();

if(isFlag){
LikeOthersEntity likeOther = likeOthersConverter.toLikeOthersEntity(collection,user);
likeOthersService.updateLike(likeOther);
collection.addLikes();
}
else{
LikeOthersEntity likeOther = likeOthersService.findByCollectionAndUser(collection,user);
likeOthersService.deleteLike(likeOther);
collection.deleteLikes();

}

return collection.getNumOfLikes();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,12 @@ public ResponseEntity<List<CollectionTitleResDTO>> getCollectionTitle(@UserSessi
public ResponseEntity<CollectionUserResDTO> getCollection(@PathVariable Long collectionId, @UserSession UsersEntity user){

return ResponseEntity.ok(collectionsBusiness.getCollection(collectionId, user));

}

@PostMapping("/collections/like")
public ResponseEntity<HashMap<String,Long>> countLike(@RequestBody CollectionLikeReqDTO likecollection,@UserSession UsersEntity user){
public ResponseEntity<HashMap<String,Long>> countLike(@RequestBody CollectionLikeReqDTO likeCollection,@UserSession UsersEntity user){
HashMap<String,Long> result = new HashMap<>();
Long numOfLikes = collectionsBusiness.updateNumOfLikes(likecollection.getCollectionId(),user);
Long numOfLikes = collectionsBusiness.updateNumOfLikes(likeCollection.getCollectionId(),user, likeCollection.isFlag());
result.put("numOfLikes", numOfLikes);
return ResponseEntity.ok(result);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@
@Builder
public class CollectionLikeReqDTO {
private long collectionId;

private boolean flag;
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,11 @@ public void addTag(TagsEntity tag) {
tag.setCollection(this);
}

public void updateLikes(){
public void addLikes(){
this.numOfLikes += 1L;
}

public void deleteLikes() {
this.numOfLikes -=1L;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,12 @@ public List<CollectionsEntity> findCollectionByUser(UsersEntity user) {
return likeOthersRepository.findCollectionByUser(user).orElseThrow(() -> new ApiException(
ErrorCode.COLLABORATOR_NOT_FOUND));
}

public void deleteLike(LikeOthersEntity likeOther) {
likeOthersRepository.delete(likeOther);
}

public LikeOthersEntity findByCollectionAndUser(CollectionsEntity collection, UsersEntity user) {
return likeOthersRepository.findByCollectionAndUser(collection,user).orElseThrow(() -> new ApiException(ErrorCode.LIKE_NOT_FOUND));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;

@Business
Expand Down Expand Up @@ -87,11 +89,19 @@ public List<SearchLinkResDTO> searchLinks(String keyword) {
* 유저가 저장한 모든 link list 불러오기
* 최신 순으로 정렬해서
*/
public List<LinkHomeResDTO> findByUserId(Long userId) {
List<LinksEntity> linkList = linksService.findByUserId(userId);
public List<LinkHomeResDTO> findByUserId(Long userId, Long lastId, int size) {
Pageable pageable = PageRequest.of(0, size);
List<LinksEntity> linkList = linksService.findByUserId(userId, lastId, pageable);

return linkList.stream()
.map(linksConverter::toLinkHomeResponse)
.collect(Collectors.toList());
}

/**
* 다음에 조회될 링크가 있는지 여부
*/
public Boolean hasNext(Long id) {
return linksService.hasNext(id);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import io.lettuce.core.dynamic.annotation.Param;
import jakarta.persistence.LockModeType;
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;
Expand All @@ -24,5 +25,7 @@ public interface LinksRepository extends JpaRepository<LinksEntity, Long> {

List<LinksEntity> findLinksEntitiesByCollection(CollectionsEntity collectionsEntity);

List<LinksEntity> findByUserIdOrderByUpdateAtDesc(Long userId);
List<LinksEntity> findByUserIdAndIdLessThanOrderByIdDesc(Long userId, Long lastId, Pageable pageable);

Boolean existsByIdLessThan(Long id);
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package com.e2i1.linkeepserver.domain.links.service;


import com.e2i1.linkeepserver.domain.collections.entity.CollectionsEntity;
import com.e2i1.linkeepserver.common.error.ErrorCode;
import com.e2i1.linkeepserver.common.exception.ApiException;
import com.e2i1.linkeepserver.domain.collections.entity.CollectionsEntity;
import com.e2i1.linkeepserver.domain.links.entity.LinksEntity;
import com.e2i1.linkeepserver.domain.links.repository.LinksRepository;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand Down Expand Up @@ -46,7 +47,11 @@ public List<LinksEntity> searchLinks(String keyword) {
return linksRepository.findByTitleOrDescriptionContainingKeyword(keyword);
}

public List<LinksEntity> findByUserId(Long userId) {
return linksRepository.findByUserIdOrderByUpdateAtDesc(userId);
public List<LinksEntity> findByUserId(Long userId, Long lastId, Pageable pageable) {
return linksRepository.findByUserIdAndIdLessThanOrderByIdDesc(userId, lastId, pageable);
}

public Boolean hasNext(Long id) {
return linksRepository.existsByIdLessThan(id);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.e2i1.linkeepserver.domain.token.entity;

import static lombok.AccessLevel.PROTECTED;

import com.e2i1.linkeepserver.common.entity.BaseEntity;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Getter
@NoArgsConstructor(access = PROTECTED)
@AllArgsConstructor
@Entity
@Table(name = "token_black_list")
public class BlackList extends BaseEntity {

private String invalidToken;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.e2i1.linkeepserver.domain.token.repository;

import com.e2i1.linkeepserver.domain.token.entity.BlackList;
import org.springframework.data.jpa.repository.JpaRepository;


public interface BlackListRepository extends JpaRepository<BlackList, Long> {

BlackList findByInvalidToken(String token);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,21 @@
import com.e2i1.linkeepserver.common.error.ErrorCode;
import com.e2i1.linkeepserver.common.exception.ApiException;
import com.e2i1.linkeepserver.domain.token.dto.TokenDTO;
import com.e2i1.linkeepserver.domain.token.entity.BlackList;
import com.e2i1.linkeepserver.domain.token.ifs.TokenHelperIfs;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import com.e2i1.linkeepserver.domain.token.repository.BlackListRepository;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@RequiredArgsConstructor
@Service
public class TokenService {

private final TokenHelperIfs tokenHelperIfs;
private final BlackListRepository blackListRepository;

public TokenDTO issueAccessToken(Long userId) {
HashMap<String, Object> data = new HashMap<>();
Expand All @@ -39,9 +41,19 @@ public Long validationToken(String token) {

// userId 없을 수 있음 -> null check
Objects.requireNonNull(userId, () -> {
throw new ApiException(ErrorCode.NULL_POINT);
throw new ApiException(ErrorCode.INVALID_TOKEN);
});

// 해당 token이 blacklist에 저장되어 있는지 확인 -> 저장되어 있으면 예외 던짐
BlackList invalidToken = blackListRepository.findByInvalidToken(token);
if (invalidToken != null) {
throw new ApiException(ErrorCode.INVALID_TOKEN, "로그아웃 된 token입니다.");
}

return Long.parseLong(userId.toString());
}

public void saveBlackList(BlackList blackList) {
blackListRepository.save(blackList);
}
}
Loading

0 comments on commit 617f999

Please sign in to comment.