Skip to content

Commit

Permalink
Merge pull request #286 from boostcampwm-2024/refactor/feed-structure
Browse files Browse the repository at this point in the history
🧼 clean: type을 추론할 수 없는 부분 찾아서 타입 명시
  • Loading branch information
CodeVac513 authored Dec 5, 2024
2 parents a0cc4f1 + e349fa7 commit c80e185
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 35 deletions.
15 changes: 5 additions & 10 deletions server/src/feed/feed.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,15 @@ import {
import { FeedService } from './feed.service';
import { QueryFeedDto } from './dto/query-feed.dto';
import { SearchFeedReq } from './dto/search-feed.dto';
import { Response } from 'express';
import { Response, Request } from 'express';
import { Observable } from 'rxjs';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { ApiReadFeedList } from './api-docs/readFeedList.api-docs';
import { ApiReadTrendFeedList } from './api-docs/readTrendFeedList.api-docs';
import { ApiSearchFeedList } from './api-docs/searchFeedList.api-docs';
import { ApiUpdateFeedViewCount } from './api-docs/updateFeedViewCount.api-docs';
import { ApiReadRecentFeedList } from './api-docs/readRecentFeedList.api-docs';
import { Feed } from './feed.entity';

@ApiTags('Feed')
@Controller('feed')
Expand Down Expand Up @@ -61,7 +62,7 @@ export class FeedController {
},
});
});
this.eventService.on('ranking-update', (trendData) => {
this.eventService.on('ranking-update', (trendData: Feed[]) => {
observer.next({
data: {
message: '새로운 트렌드 피드 수신 완료',
Expand Down Expand Up @@ -92,16 +93,10 @@ export class FeedController {
@UsePipes(new ValidationPipe({ transform: true }))
async updateFeedViewCount(
@Param('feedId') feedId: number,
@Req() request,
@Req() request: Request,
@Res({ passthrough: true }) response: Response,
) {
const cookie = request.headers.cookie;
const ip =
request.headers['CF-Connecting-IP'] ||
request.headers['x-forwarded-for'] ||
request.socket?.remoteAddress ||
'unknown';
await this.feedService.updateFeedViewCount(feedId, ip, cookie, response);
await this.feedService.updateFeedViewCount(feedId, request, response);
return ApiResponse.responseWithNoContent(
'요청이 성공적으로 처리되었습니다.',
);
Expand Down
66 changes: 41 additions & 25 deletions server/src/feed/feed.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
SearchFeedRes,
SearchFeedResult,
} from './dto/search-feed.dto';
import { Response } from 'express';
import { Response, Request } from 'express';
import { cookieConfig } from '../common/cookie/cookie.config';
import { redisKeys } from '../common/redis/redis.constant';

Expand Down Expand Up @@ -125,33 +125,49 @@ export class FeedService {
return searchType.hasOwnProperty(type);
}

async updateFeedViewCount(feedId: number, ip: string, cookie, response) {
const redis = this.redisService.redisClient;
const [feed, hasCookie, hasIpFlag] = await Promise.all([
this.feedRepository.findOne({ where: { id: feedId } }),
Boolean(cookie?.[`View_count_${feedId}`]),
redis.sismember(`feed:${feedId}:ip`, ip),
]);
async updateFeedViewCount(
feedId: number,
request: Request,
response: Response,
) {
const cookie = request.headers.cookie;
const ip =
request.headers['CF-Connecting-IP'] ||
request.headers['x-forwarded-for'] ||
request.socket?.remoteAddress ||
'unknown';
if (ip && this.isString(ip)) {
const redis = this.redisService.redisClient;
const [feed, hasCookie, hasIpFlag] = await Promise.all([
this.feedRepository.findOne({ where: { id: feedId } }),
Boolean(cookie?.includes(`View_count_${feedId}=${feedId}`)),
redis.sismember(`feed:${feedId}:ip`, ip),
]);

if (!feed) {
throw new NotFoundException(`${feedId}번 피드를 찾을 수 없습니다.`);
}

if (!feed) {
throw new NotFoundException(`${feedId}번 피드를 찾을 수 없습니다.`);
}
if (!hasCookie) {
this.createCookie(response, feedId);
}

if (!hasCookie) {
this.createCookie(response, feedId);
}
if (hasCookie || hasIpFlag) {
return null;
}

if (hasCookie || hasIpFlag) {
return null;
await Promise.all([
redis.sadd(`feed:${feedId}:ip`, ip),
this.feedRepository.update(feedId, {
viewCount: () => 'view_count + 1',
}),
redis.zincrby(redisKeys.FEED_TREND_KEY, 1, feedId.toString()),
]);
}
}

await Promise.all([
redis.sadd(`feed:${feedId}:ip`, ip),
this.feedRepository.update(feedId, {
viewCount: () => 'view_count + 1',
}),
redis.zincrby(redisKeys.FEED_TREND_KEY, 1, feedId.toString()),
]);
private isString(ip: string | string[]): ip is string {
return !Array.isArray(ip);
}

private createCookie(response: Response, feedId: number) {
Expand Down Expand Up @@ -182,7 +198,7 @@ export class FeedService {

async readRecentFeedList() {
const redis = this.redisService.redisClient;
const recentFeedList = [];
const recentFeedList: Feed[] = [];
if ((await redis.get(redisKeys.FEED_RECENT_KEY)) === 'true') {
const keys = await redis.keys(redisKeys.FEED_RECENT_ALL_KEY);
if (keys.length <= 0) {
Expand All @@ -193,7 +209,7 @@ export class FeedService {
pipeLine.hgetall(key);
}
const result = await pipeLine.exec();
recentFeedList.push(...result.map(([, data]) => data));
recentFeedList.push(...result.map(([, data]) => data as Feed));
}

return recentFeedList.sort((currentFeed, nextFeed) => {
Expand Down

0 comments on commit c80e185

Please sign in to comment.