Skip to content

Commit

Permalink
[v1.0.3] user eager option false로 ... 쿼리 속도저하 개선
Browse files Browse the repository at this point in the history
[v1.0.3] user eager option false로 ... 쿼리 속도저하 개선
  • Loading branch information
ImNM authored Aug 6, 2022
2 parents 5a1e74a + f5f8434 commit ebb3256
Show file tree
Hide file tree
Showing 9 changed files with 71 additions and 48 deletions.
3 changes: 3 additions & 0 deletions src/auth/auth.interface.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Role } from 'src/common/consts/enum';

export interface RegisterJwtPayload {
phoneNumber: string;
}
Expand All @@ -6,4 +8,5 @@ export interface AccessJwtPayload {
phoneNumber: string;
name: string;
id: number;
role: Role;
}
14 changes: 9 additions & 5 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,8 @@ export class AuthService {
const accessToken = this.accessJwtSign({
id: user.id,
phoneNumber: user.phoneNumber,
name: user.name
name: user.name,
role: user.role
});
//console.log(accessToken);

Expand Down Expand Up @@ -180,7 +181,8 @@ export class AuthService {
const accessToken = this.accessJwtSign({
id: signUser.id,
phoneNumber: signUser.phoneNumber,
name: signUser.name
name: signUser.name,
role: signUser.role
});

await queryRunner.commitTransaction();
Expand Down Expand Up @@ -289,7 +291,8 @@ export class AuthService {
const accessToken = this.accessJwtSign({
id: searchUser.id,
phoneNumber: searchUser.phoneNumber,
name: searchUser.name
name: searchUser.name,
role: searchUser.role
});
return {
user: searchUser,
Expand Down Expand Up @@ -371,12 +374,13 @@ export class AuthService {
| string
) &
AccessJwtPayload;
const { phoneNumber, id, name } = payload;
const { phoneNumber, id, name, role } = payload;

return {
id,
phoneNumber,
name
name,
role
};
} catch (e) {
if (e.name === 'TokenExpiredError')
Expand Down
5 changes: 3 additions & 2 deletions src/auth/guards/AccessToken.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class AccessTokenGuard implements CanActivate {
context: ExecutionContext
): boolean | Promise<boolean> | Observable<boolean> {
//@NoAuth 사용시 해당 부분에서 AccessTokenGuard 사용 해제시킴
const noAuth = this.reflector.get<boolean>('no-auth', context.getHandler())
const noAuth = this.reflector.get<boolean>('no-auth', context.getHandler());
if (noAuth) {
return true;
}
Expand Down Expand Up @@ -56,7 +56,8 @@ export class AccessTokenGuard implements CanActivate {

const payload = this.authService.verifyAccessJWT(jwtString);

const user = await this.authService.findUserById(payload.id);
// const user = payload
const user = payload;
if (!user) {
throw new UnauthorizedException(
AuthErrorDefine['Auth-1003'],
Expand Down
3 changes: 2 additions & 1 deletion src/common/decorators/user.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { AccessJwtPayload } from 'src/auth/auth.interface';

export const ReqUser = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
// //console.log('asdfasdfasd');

const userObj = request.user;
const userObj = request.user as AccessJwtPayload;

return userObj;
}
Expand Down
12 changes: 6 additions & 6 deletions src/database/entities/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,24 +52,24 @@ export class User {
})
public role: Role;

@OneToMany(type => Comment, comment => comment.user, { eager: true })
public comments: Comment[];
@OneToMany(type => Comment, comment => comment.user, { eager: false })
public comments: Comment[] | null;

@ApiProperty({
description: '유저의 주문목록',
type: () => [Order]
})
@Expose()
@OneToMany(type => Order, order => order.user, { eager: true })
public order: Order[];
@OneToMany(type => Order, order => order.user, { eager: false })
public order: Order[] | null;

@ApiProperty({
description: '유저의 티켓목록',
type: () => [Ticket]
})
@Expose()
@OneToMany(type => Ticket, ticket => ticket.user, { eager: true })
public ticket: Ticket[];
@OneToMany(type => Ticket, ticket => ticket.user, { eager: false })
public ticket: Ticket[] | null;

@ApiProperty({
description: '유저 생성 일자',
Expand Down
17 changes: 8 additions & 9 deletions src/database/repositories/user.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class UserRepository {
) {}

async getMyInfo(user: User) {
return await this.userRepository.findOne({ where : {id: user.id}});
return await this.userRepository.findOne({ where: { id: user.id } });
}

async findByPhoneNumber(phoneNumber: string): Promise<User | null> {
Expand Down Expand Up @@ -57,7 +57,7 @@ export class UserRepository {

// 유저 정보 조회(관리자용) 전체 정보 조회
async getAllUserInfo(
userFindDto: UserFindDto,
userFindDto: UserFindDto,
pageOptionsDto: PageOptionsDto
) {
const { searchName, phoneNumber } = userFindDto;
Expand All @@ -82,18 +82,18 @@ export class UserRepository {
.addSelect('ticket')
.skip(pageOptionsDto.skip)
.take(pageOptionsDto.take);

const itemCount = await queryBuilder.getCount();
const { entities } = await queryBuilder.getRawAndEntities();

const pageMetaDto = new PageMetaDto({ itemCount, pageOptionsDto })
return new PageDto(entities, pageMetaDto);
const pageMetaDto = new PageMetaDto({ itemCount, pageOptionsDto });

return new PageDto(entities, pageMetaDto);
}

// 입금자명 수정
async changeName(id: number, requestUserNameDto: RequestUserNameDto) {
const found = await this.userRepository.findOne({ where: {id: id}});
const found = await this.userRepository.findOne({ where: { id: id } });

if (!found) {
throw new NotFoundException('해당 유저가 존재하지 않습니다.');
Expand All @@ -105,5 +105,4 @@ export class UserRepository {
await this.userRepository.save(found);
return plainToInstance(UserProfileDto, found);
}

}
}
8 changes: 4 additions & 4 deletions src/tickets/tickets.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { NoAuth } from 'src/auth/guards/NoAuth.guard';
import { TicketCountDto } from './dtos/ticket-count.dto';
import { ErrorResponse } from 'src/common/decorators/ErrorResponse.decorator';
import { TicketEntryResponseDto } from './dtos/ticket-entry-response.dto';
import { AccessJwtPayload } from 'src/auth/auth.interface';

@ApiTags('tickets')
@ApiBearerAuth('accessToken')
Expand Down Expand Up @@ -155,7 +156,7 @@ export class TicketsController {
@Patch('/status')
updateTicketStatus(
@Body('') updateTicketStatusDto: UpdateTicketStatusDto,
@ReqUser() user: User
@ReqUser() user: AccessJwtPayload
) {
return this.ticketService.updateTicketStatus(updateTicketStatusDto, user);
}
Expand All @@ -176,7 +177,7 @@ export class TicketsController {
getTicketByUuid(
@Param('uuid')
uuid: string,
@ReqUser() user: User
@ReqUser() user: AccessJwtPayload
) {
//console.log(user);
return this.ticketService.findByUuid(uuid, user);
Expand Down Expand Up @@ -279,7 +280,6 @@ export class TicketsController {
return this.ticketService.deleteTicketByUuid(ticketUuid);
}


// /* 테스트용 라우팅 */
// @ApiOperation({
// summary: '[테스트용, 삭제예정]조건없이 모든 티켓을 불러온다'
Expand All @@ -298,7 +298,7 @@ export class TicketsController {
// getAllTickets() {
// return this.ticketService.findAll();
// }

// @ApiOperation({ summary: '[테스트용] 임시 티켓 생성' })
// @ApiResponse({
// status: 200,
Expand Down
9 changes: 6 additions & 3 deletions src/tickets/tickets.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { CreateTicketDto } from './dtos/create-ticket.dto';
import { TicketEntryResponseDto } from './dtos/ticket-entry-response.dto';
import { TicketFindDto } from './dtos/ticket-find.dto';
import { UpdateTicketStatusDto } from './dtos/update-ticket-status.dto';
import { AccessJwtPayload } from 'src/auth/auth.interface';

@Injectable()
export class TicketsService {
Expand All @@ -42,7 +43,10 @@ export class TicketsService {
* @param user Request User
* @returns Ticket Promise
*/
async findByUuid(ticketUuid: string, user: User): Promise<Ticket | null> {
async findByUuid(
ticketUuid: string,
user: AccessJwtPayload
): Promise<Ticket | null> {
const ticket = await this.ticketRepository.findByUuid(ticketUuid);

//어드민이거나 Ticket.user.id === user.id 일때만 리턴
Expand Down Expand Up @@ -124,7 +128,7 @@ export class TicketsService {
return '입금 기한이 만료된 티켓입니다';
} else if (status == TicketStatus.ORDERWAIT) {
return '입금 대기중인 티켓입니다';
}
}
return '검증 오류';
};

Expand All @@ -137,7 +141,6 @@ export class TicketsService {

// 티켓 상태 오류('입장대기'가 아님)
if (ticket.status !== TicketStatus.ENTERWAIT) {

response.message = '[입장실패]' + getFailureMessage(ticket.status);
this.socketService.emitToAll(response);
throw new BadRequestException(getFailureMessage(ticket.status));
Expand Down
48 changes: 30 additions & 18 deletions src/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,31 @@ export class UsersService {
async findUserById(id: number): Promise<User | null> {
return await this.userRepository.findUserById(id);
}

// 유저 정보 조회(관리자용) 전체 정보 조회
async getAllUserInfo(userFindDto: UserFindDto, pageOptionsDto: PageOptionsDto) {
const pageDto = await this.userRepository.getAllUserInfo(userFindDto, pageOptionsDto);
async getAllUserInfo(
userFindDto: UserFindDto,
pageOptionsDto: PageOptionsDto
) {
const pageDto = await this.userRepository.getAllUserInfo(
userFindDto,
pageOptionsDto
);
const pageMetaData = pageDto.meta;
const users = pageDto.data;
const ret_users = users.map(function(user) {
const ret_users = users.map(function (user) {
const userProfile = {
id: user.id,
name: user.name,
phoneNumber: user.phoneNumber,
role: user.role,
createAt: user.createdAt,
ticketNum: user.ticket.length
}
ticketNum: user.ticket?.length
};
return userProfile;
})
const entities = plainToInstance(ResponseUserTicketNumDto, ret_users)
});
const entities = plainToInstance(ResponseUserTicketNumDto, ret_users);

return new PageDto(entities, pageMetaData);
}

Expand All @@ -69,28 +75,34 @@ export class UsersService {

// 모든 댓글 조회
async getAllComment(userId: number, scrollOptionsDto: ScrollOptionsDto) {
const responseScrollCommentDto = await this.commentRepository.getAllComment(userId, scrollOptionsDto);
const responseScrollCommentDto = await this.commentRepository.getAllComment(
userId,
scrollOptionsDto
);
const comments = responseScrollCommentDto.list;
const ret_comments = comments.map(function(comment) {
const ret_comments = comments.map(function (comment) {
const responseCommentDto = {
...comment,
iUserId: userId
}
return responseCommentDto;
}
)
};
return responseCommentDto;
});
const final_comments = plainToInstance(ResponseCommentDto, ret_comments);
return new ResponseScrollCommentsDto(final_comments, responseScrollCommentDto.meta);
return new ResponseScrollCommentsDto(
final_comments,
responseScrollCommentDto.meta
);
}

// 댓글 랜덤 조회
async getRandomComment(requestRandomCommentDto: RequestRandomCommentDto) {
return await this.commentRepository.getRandomComment(requestRandomCommentDto);
return await this.commentRepository.getRandomComment(
requestRandomCommentDto
);
}

// 댓글 삭제
async deleteComment(id: number) {
return await this.commentRepository.deleteComment(id);
}

}

0 comments on commit ebb3256

Please sign in to comment.