Skip to content
This repository has been archived by the owner on May 14, 2024. It is now read-only.

Commit

Permalink
Refactor: 탐색 메인 api 분리 및 닉네임 누락 해결 #222 (#229)
Browse files Browse the repository at this point in the history
## 요약

<br><br>

## 작업 내용

- [x] 탐색탭 api 분리
- [x] 카카오 로그인 닉네임 누락 해결
- [x] 토큰없이 api 접근하기 구현

<br><br>

## 참고 사항

<br><br>

## 관련 이슈

- Close #222

<br><br>
  • Loading branch information
JangYouJung committed Feb 15, 2024
2 parents c1d95eb + 5f92480 commit 9ce8be8
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 22 deletions.
3 changes: 1 addition & 2 deletions src/search/dto/get-search-main.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@
import { SignatureCoverDto } from './signature-cover.dto';

export class GetSearchMainDto{
hot: SignatureCoverDto[];
new: SignatureCoverDto[];
covers: SignatureCoverDto[];
}
50 changes: 38 additions & 12 deletions src/search/search.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,58 @@ import { SignatureCoverDto } from './dto/signature-cover.dto';
import { SearchService } from './search.service';
import { UserGuard } from '../user/user.guard';
import { Request } from 'express';
import { OptionalUserGuard } from '../user/optional.user.guard';

@Controller('search')
export class SearchController{

constructor(private readonly searchService: SearchService) {}

@Get('/') // 팀색탭 메인: 인기 급상승, 메이트의 최신 시그니처
@UseGuards(UserGuard)
async getSearchMain(
@Req() req: Request,
@Get('/hot') // 팀색탭 메인: 인기 급상승 시그니처
async getSearchHotSignatures(
): Promise<ResponseDto<GetSearchMainDto>>{
try{
const getSearchMainDto:GetSearchMainDto = new GetSearchMainDto();
const getHotSignaturesDto:GetSearchMainDto = new GetSearchMainDto();

// [1] 인기 급상승 시그니처 가져오기
const hotSignatures:SignatureCoverDto[] = await this.searchService.findHotSignatures();
getSearchMainDto.hot = hotSignatures;
// 인기 급상승 시그니처 가져오기
getHotSignaturesDto.covers = await this.searchService.findHotSignatures();

// [2] 내가 팔로우하는 메이트들의 최신 시그니처 가져오기
const newSignatures:SignatureCoverDto[] = await this.searchService.findMatesNewSignatures(req.user.id);
getSearchMainDto.new = newSignatures;
return new ResponseDto(
ResponseCode.GET_SEARCH_MAIN_SUCCESS,
true,
"탐색탭 메인 화면 가져오기 성공",
getHotSignaturesDto
);
}catch (error){
console.log("탐색탭 메인 가져오기 실패: ", error);
return new ResponseDto(
ResponseCode.GET_SEARCH_MAIN_FAIL,
false,
"탐색탭 메인 화면 가져오기 실패",
null
);
}
}

@Get('/new') // 팀색탭 메인: 인기 급상승, 메이트의 최신 시그니처
@UseGuards(OptionalUserGuard)
async getSearchNewSignatures(
@Req() req?: Request,
): Promise<ResponseDto<GetSearchMainDto>>{
try{
const getMatesNewSignatureDto:GetSearchMainDto = new GetSearchMainDto();

// 로그인 했을 경우 내가 팔로우하는 메이트들의 최신 시그니처 가져오기
if(req.user != null) getMatesNewSignatureDto.covers = await this.searchService.findMatesNewSignatures(req.user.id);

// 로그인 안했으면 빈 배열
else getMatesNewSignatureDto.covers = null;

return new ResponseDto(
ResponseCode.GET_SEARCH_MAIN_SUCCESS,
true,
"탐색탭 메인 화면 가져오기 성공",
getSearchMainDto
getMatesNewSignatureDto
);
}catch (error){
console.log("탐색탭 메인 가져오기 실패: ", error);
Expand All @@ -47,6 +72,7 @@ export class SearchController{
}
}


@Get('/find') // 탑색탭 검색: 키워드로 시그니처 검색하기
async search(@Query('keyword') keyword: string): Promise<ResponseDto<SignatureCoverDto[]>> {
try{
Expand Down
4 changes: 2 additions & 2 deletions src/search/search.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export class SearchService{
/********************************************************
내 메이트 최신 시그니처 로직:
[1] 내가 팔로우하고 있는 메이트 목록 가져오기
[2] 각 메이트가 작성한 시그니처 중 일주일 안으로 작성된 것만 가져오기
[2] 각 메이트가 작성한 시그니처 중 20일 안으로 작성된 가져오기
[3] 최신순으로 정렬해서 20개만 리턴
********************************************************/

Expand Down Expand Up @@ -121,7 +121,7 @@ export class SearchService{
signatureCover._id = signature.id;
signatureCover.title = signature.title;
signatureCover.liked = signature.liked;
signatureCover.userName = signature.user.name;
signatureCover.userName = signature.user.nickname;

// 시그니처 썸네일 이미지 가져오기
signatureCover.date = await SignatureEntity.formatDateString(signature.created);
Expand Down
12 changes: 6 additions & 6 deletions src/signature/domain/signature.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,14 +137,14 @@ export class SignatureEntity extends BaseEntity implements EntitySubscriberInter
}

static async findNewSignaturesByUser(userId: number) {
// [1] 기준이 되는 일주일 전 날짜
const sevenDaysAgo: Date = new Date();
sevenDaysAgo.setDate(sevenDaysAgo.getDate()-7);
console.log(sevenDaysAgo);
// [1] 기준이 되는 20일 전 날짜
const twentyDaysAgo: Date = new Date();
twentyDaysAgo.setDate(twentyDaysAgo.getDate()-20);
console.log(twentyDaysAgo);

// [2] 일주일 전에 쓰인 메이트의 최신 시그니처 가져오기
// [2] 20일 전에 쓰인 메이트의 최신 시그니처 가져오기
const signatures = await SignatureEntity.find({
where:{user:{id: userId}, created: MoreThan(sevenDaysAgo)},
where:{user:{id: userId}, created: MoreThan(twentyDaysAgo)},
relations: ['user'] // user 포함
})
return signatures;
Expand Down
47 changes: 47 additions & 0 deletions src/user/optional.user.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import Express from 'express';
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import * as jsonwebtoken from 'jsonwebtoken';
import { IReqUser } from './user.dto';
import { UserEntity } from './user.entity';

@Injectable()
export class OptionalUserGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Express.Request>();
const authorization = request.headers['authorization']?.split(' ');

if (
authorization &&
authorization.length === 2 &&
authorization[0] === 'Bearer'
) {
const token = authorization[1];

try {
request.user = jsonwebtoken.verify(
token,
process.env.JWT_SECRET,
) as IReqUser;

// 사용자 검증
const isValidUser = await UserEntity.findOne({
where: {
id: request.user.id,
isQuit: false,
},
});

if (!isValidUser) {
return false;
}
} catch (error) {
return false;
}
}
else{ // 토큰이 없는 경우
request.user = null;
}

return true;
}
}

0 comments on commit 9ce8be8

Please sign in to comment.