Skip to content

Commit

Permalink
Merge pull request #11 from boostcampwm-2024/refactor/clean-code
Browse files Browse the repository at this point in the history
🧼 clean: 코드 일관성 향상
  • Loading branch information
Jo-Minseok authored Jan 13, 2025
2 parents 98cfa15 + 68a339a commit 824225d
Show file tree
Hide file tree
Showing 22 changed files with 104 additions and 112 deletions.
8 changes: 4 additions & 4 deletions feed-crawler/src/repository/feed.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,16 @@ export class FeedRepository {
const promiseResults = await Promise.all(insertPromises);

const insertedFeeds = promiseResults
.map((result: any, index) => {
if (result) {
const insertId = result.insertId;
.map((feed: any, index) => {
if (feed) {
const insertId = feed.insertId;
return {
...resultData[index],
id: insertId,
};
}
})
.filter((result) => result);
.filter((feed) => feed);

logger.info(
`[MySQL] ${insertedFeeds.length}개의 피드 데이터가 성공적으로 데이터베이스에 삽입되었습니다.`,
Expand Down
5 changes: 0 additions & 5 deletions server/src/admin/controller/admin.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import {
Req,
Res,
UseGuards,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { AdminService } from '../service/admin.service';
Expand All @@ -31,7 +29,6 @@ export class AdminController {
@ApiLoginAdmin()
@Post('/login')
@HttpCode(HttpStatus.OK)
@UsePipes(ValidationPipe)
async loginAdmin(
@Body() loginAdminDto: LoginAdminRequestDto,
@Res({ passthrough: true }) response: Response,
Expand Down Expand Up @@ -60,7 +57,6 @@ export class AdminController {
@ApiCreateAdmin()
@UseGuards(CookieAuthGuard)
@Post('/register')
@UsePipes(ValidationPipe)
async createAdmin(@Body() registerAdminDto: RegisterAdminRequestDto) {
await this.adminService.createAdmin(registerAdminDto);
return ApiResponse.responseWithNoContent(
Expand All @@ -72,7 +68,6 @@ export class AdminController {
@Get('/sessionId')
@HttpCode(HttpStatus.OK)
@UseGuards(CookieAuthGuard)
@UsePipes(new ValidationPipe({ transform: true }))
async readSessionIdAdmin() {
return ApiResponse.responseWithNoContent('정상적인 sessionId 입니다.');
}
Expand Down
4 changes: 2 additions & 2 deletions server/src/admin/dto/request/login-admin.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ApiProperty } from '@nestjs/swagger';

export class LoginAdminRequestDto {
@ApiProperty({
example: 'minseokjo',
example: 'test',
description: '관리자 로그인 아이디를 입력해주세요.',
})
@IsNotEmpty({
Expand All @@ -15,7 +15,7 @@ export class LoginAdminRequestDto {
loginId: string;

@ApiProperty({
example: 'heisgoat123!',
example: 'test1234!',
description: '패스워드를 입력해주세요.',
})
@IsNotEmpty({
Expand Down
4 changes: 2 additions & 2 deletions server/src/admin/dto/request/register-admin.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const PASSWORD_REG = /^(?=.*[!@#$%^&*()_+])[A-Za-z0-9!@#$%^&*()_+]+$/;

export class RegisterAdminRequestDto {
@ApiProperty({
example: 'minseokjo',
example: 'test',
description: '관리자 로그인 아이디를 입력해주세요.',
})
@IsString({
Expand All @@ -17,7 +17,7 @@ export class RegisterAdminRequestDto {
loginId: string;

@ApiProperty({
example: 'heisgoat123!',
example: 'test1234!',
description:
'패스워드를 입력해주세요. (최소 6자, 영문/숫자/특수문자로 이루어질 수 있으며 특수문자 1개 이상 포함)',
})
Expand Down
4 changes: 2 additions & 2 deletions server/src/feed/api-docs/searchFeedList.api-docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function ApiSearchFeedList() {
required: true,
type: String,
description: '검색어',
example: '데나무',
example: 'test',
}),
ApiQuery({
name: 'type',
Expand Down Expand Up @@ -96,7 +96,7 @@ export function ApiSearchFeedList() {
{
id: 1,
blogName: '블로그 이름',
title: '데나무',
title: 'test',
path: 'https://test.com/1',
createdAt: '2024-10-27T02:08:55.000Z',
},
Expand Down
8 changes: 0 additions & 8 deletions server/src/feed/api-docs/updateFeedViewCount.api-docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,13 @@ import {
ApiNotFoundResponse,
ApiOkResponse,
ApiOperation,
ApiParam,
} from '@nestjs/swagger';

export function ApiUpdateFeedViewCount() {
return applyDecorators(
ApiOperation({
summary: `피드 조회수 업데이트 API`,
}),
ApiParam({
name: 'feedId',
required: true,
type: Number,
description: '클릭한 피드의 id',
example: 1,
}),
ApiOkResponse({
description: 'Ok',
schema: {
Expand Down
29 changes: 11 additions & 18 deletions server/src/feed/controller/feed.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import {
Req,
Res,
Sse,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { FeedService } from '../service/feed.service';
import { FeedPaginationRequestDto } from '../dto/request/feed-pagination.dto';
Expand All @@ -26,6 +24,7 @@ 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 { FeedTrendResponseDto } from '../dto/response/feed-pagination.dto';
import { FeedViewUpdateRequestDto } from '../dto/request/feed-update.dto';

@ApiTags('Feed')
@Controller('feed')
Expand All @@ -38,11 +37,6 @@ export class FeedController {
@ApiReadFeedPagination()
@Get('')
@HttpCode(HttpStatus.OK)
@UsePipes(
new ValidationPipe({
transform: true,
}),
)
async readFeedPagination(@Query() queryFeedDto: FeedPaginationRequestDto) {
return ApiResponse.responseWithData(
'피드 조회 완료',
Expand Down Expand Up @@ -81,27 +75,26 @@ export class FeedController {
@ApiSearchFeedList()
@Get('search')
@HttpCode(HttpStatus.OK)
@UsePipes(
new ValidationPipe({
transform: true,
}),
new ValidationPipe(),
)
async searchFeedList(@Query() searchFeedReq: SearchFeedRequestDto) {
const data = await this.feedService.searchFeedList(searchFeedReq);
return ApiResponse.responseWithData('검색 결과 조회 완료', data);
return ApiResponse.responseWithData(
'검색 결과 조회 완료',
await this.feedService.searchFeedList(searchFeedReq),
);
}

@ApiUpdateFeedViewCount()
@Post('/:feedId')
@HttpCode(HttpStatus.OK)
@UsePipes(new ValidationPipe({ transform: true }))
async updateFeedViewCount(
@Param('feedId') feedId: number,
@Param() params: FeedViewUpdateRequestDto,
@Req() request: Request,
@Res({ passthrough: true }) response: Response,
) {
await this.feedService.updateFeedViewCount(feedId, request, response);
await this.feedService.updateFeedViewCount(
params.feedId,
request,
response,
);
return ApiResponse.responseWithNoContent(
'요청이 성공적으로 처리되었습니다.',
);
Expand Down
15 changes: 15 additions & 0 deletions server/src/feed/dto/request/feed-update.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsInt } from 'class-validator';

export class FeedViewUpdateRequestDto {
@ApiProperty({
example: 1,
description: '조회할 ID 입력',
})
@IsInt({
message: '정수를 입력해주세요.',
})
@Type(() => Number)
feedId: number;
}
8 changes: 6 additions & 2 deletions server/src/feed/dto/response/feed-pagination.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,12 @@ export class FeedPaginationResponseDto {
private hasMore: boolean,
) {}

static toResponseDto(result: FeedResult[], lastId: number, hasMore: boolean) {
return new FeedPaginationResponseDto(result, lastId, hasMore);
static toResponseDto(
feedPagination: FeedResult[],
lastId: number,
hasMore: boolean,
) {
return new FeedPaginationResponseDto(feedPagination, lastId, hasMore);
}
}

Expand Down
20 changes: 12 additions & 8 deletions server/src/feed/service/feed.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,12 @@ export class FeedService {
if (hasMore) feedList.pop();
const lastId = this.getLastIdFromFeedList(feedList);
const newCheckFeedList = await this.checkNewFeeds(feedList);
const result = FeedResult.toResultDtoArray(newCheckFeedList);
return FeedPaginationResponseDto.toResponseDto(result, lastId, hasMore);
const feedPagination = FeedResult.toResultDtoArray(newCheckFeedList);
return FeedPaginationResponseDto.toResponseDto(
feedPagination,
lastId,
hasMore,
);
}

private existNextFeed(feedList: FeedView[], limit: number) {
Expand All @@ -62,8 +66,8 @@ export class FeedService {
const newFeedIds = (
await this.redisService.keys(redisKeys.FEED_RECENT_ALL_KEY)
).map((key) => {
const id = key.match(/feed:recent:(\d+)/);
return parseInt(id[1]);
const feedId = key.match(/feed:recent:(\d+)/);
return parseInt(feedId[1]);
});

return feedList.map((feed): FeedPaginationResult => {
Expand Down Expand Up @@ -98,14 +102,14 @@ export class FeedService {
throw new BadRequestException('검색 타입이 잘못되었습니다.');
}

const [result, totalCount] = await this.feedRepository.searchFeedList(
const [searchResult, totalCount] = await this.feedRepository.searchFeedList(
find,
limit,
type,
offset,
);

const feeds = SearchFeedResult.toResultDtoArray(result);
const feeds = SearchFeedResult.toResultDtoArray(searchResult);
const totalPages = Math.ceil(totalCount / limit);

return SearchFeedResponseDto.toResponseDto(
Expand Down Expand Up @@ -195,13 +199,13 @@ export class FeedService {
return [];
}

const result = await this.redisService.executePipeline((pipeline) => {
const recentFeeds = await this.redisService.executePipeline((pipeline) => {
for (const key of recentKeys) {
pipeline.hgetall(key);
}
});

let recentFeedList: FeedRecentRedis[] = result.map(
let recentFeedList: FeedRecentRedis[] = recentFeeds.map(
([, feed]: [any, FeedRecentRedis]) => {
return { ...feed, isNew: true };
},
Expand Down
2 changes: 2 additions & 0 deletions server/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import * as cookieParser from 'cookie-parser';
import { InternalExceptionsFilter } from './common/filters/internal-exceptions.filter';
import { LoggingInterceptor } from './common/logger/logger.interceptor';
import { WinstonLoggerService } from './common/logger/logger.service';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
Expand All @@ -17,6 +18,7 @@ async function bootstrap() {
new InternalExceptionsFilter(logger),
new HttpExceptionsFilter(),
);
app.useGlobalPipes(new ValidationPipe({ transform: true }));
app.enableCors({
origin: [
'http://localhost:5173',
Expand Down
12 changes: 2 additions & 10 deletions server/src/rss/controller/rss.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ import {
Get,
HttpCode,
Param,
ParseIntPipe,
Post,
UsePipes,
ValidationPipe,
UseGuards,
} from '@nestjs/common';
import { CookieAuthGuard } from '../../common/guard/auth.guard';
Expand All @@ -31,7 +28,6 @@ export class RssController {

@ApiCreateRss()
@Post()
@UsePipes(ValidationPipe)
async createRss(@Body() rssRegisterDto: RssRegisterRequestDto) {
await this.rssService.createRss(rssRegisterDto);
return ApiResponse.responseWithNoContent('신청이 완료되었습니다.');
Expand All @@ -49,26 +45,22 @@ export class RssController {

@ApiAcceptRss()
@UseGuards(CookieAuthGuard)
@UsePipes(new ValidationPipe({ transform: true }))
@Post('accept/:id')
@HttpCode(201)
async acceptRss(@Param() params: RssManagementRequestDto) {
const { id } = params;
await this.rssService.acceptRss(id);
await this.rssService.acceptRss(params.id);
return ApiResponse.responseWithNoContent('승인이 완료되었습니다.');
}

@ApiRejectRss()
@UsePipes(ValidationPipe)
@UseGuards(CookieAuthGuard)
@Post('reject/:id')
@HttpCode(201)
async rejectRss(
@Body() body: RejectRssRequestDto,
@Param() params: RssManagementRequestDto,
) {
const { id } = params;
await this.rssService.rejectRss(id, body.description);
await this.rssService.rejectRss(params.id, body.description);
return ApiResponse.responseWithNoContent('거절이 완료되었습니다.');
}

Expand Down
6 changes: 3 additions & 3 deletions server/src/rss/dto/request/rss-register.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class RssRegisterRequestDto {
blog: string;

@ApiProperty({
example: 'J235_조민석',
example: 'test',
description: '실명을 입력해주세요.',
})
@Length(2, 50, { message: '이름 길이가 올바르지 않습니다.' })
Expand All @@ -29,7 +29,7 @@ export class RssRegisterRequestDto {
name: string;

@ApiProperty({
example: 'seok3765@naver.com',
example: 'test@test.com',
description: '이메일을 입력해주세요.',
})
@IsEmail(
Expand All @@ -44,7 +44,7 @@ export class RssRegisterRequestDto {
email: string;

@ApiProperty({
example: 'https://v2.velog.io/rss/@seok3765',
example: 'https://test.com/rss',
description: 'RSS 주소를 입력해주세요.',
})
@IsUrl(
Expand Down
Loading

0 comments on commit 824225d

Please sign in to comment.