• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

followeeCount, followerCount 증가, 감소를 위한 메소드 일반화하기 코드 공유

24.01.30 19:30 작성 조회수 118

0

 

increment(conditions: FindOptionsWhere<Entity>, propertyPath: string, value: number | string)

먼저 increment메소드의 propertyPath 부분이 특정 Model의 프로퍼티를 추론 하지 않고 string으로 박혀 있는게 마음에 들지 않아서 대상이 되는 프로퍼티 필드 명을 추론 하게 작성 했습니다.

// users.service.ts
async incrementFollowerCount(
    userId: number,
    fieldName: keyof Pick<UsersModel, 'followerCount' | 'followeeCount'>,
    incrementCount: number,
    qr?: QueryRunner,
  ) {
    const usersRepository = this.getUsersRepository(qr);

    await usersRepository.increment(
      {
        id: userId,
      },
      fieldName,
      incrementCount,
    );
  }

1. fieldName: 어떤 프로퍼티를 증가, 감소를 할것인지 특정하는 파라미터

2. incrementCount : 몇 증가 시킬것인지 증가 value

// users.service.ts
async decrementFollowerCount(
    userId: number,
    fieldName: keyof Pick<UsersModel, 'followerCount' | 'followeeCount'>,
    decrementCount: number,
    qr?: QueryRunner,
  ) {
    const usersRepository = this.getUsersRepository(qr);

    await usersRepository.decrement(
      {
        id: userId,
      },
      fieldName,
      decrementCount,
    );
  }
  • contoller에서 사용하기

// users.controller.ts
@Patch('follow/:id/confirm')
  @UseInterceptors(TransactionInterceptoer)
  async patchFollowConfirm(
    @User() user: UsersModel,
    @Param('id', ParseIntPipe) followerId: number,
    @QueryRunnerDecorator() qr: QueryRunner,
  ) {
    await this.usersService.confirmFollow(followerId, user.id);

    await this.usersService.incrementFollowerCount(
      user.id,
      'followerCount',
      1,
      qr,
    );

    await this.usersService.incrementFollowerCount(
      followerId,
      'followeeCount',
      1,
      qr,
    );

    return true;
  }

@Delete('follow/:id')
  @UseInterceptors(TransactionInterceptoer)
  async deleteFollow(
    @User() user: UsersModel,
    @Param('id', ParseIntPipe) followeeId: number,
    @QueryRunnerDecorator() qr: QueryRunner,
  ) {
    await this.usersService.deleteFollow(user.id, followeeId);

    await this.usersService.decrementFollowerCount(
      user.id,
      'followerCount',
      1,
      qr,
    );

    await this.usersService.decrementFollowerCount(
      followeeId,
      'followeeCount',
      1,
      qr,
    );
    return true;
  }

filedName 파라미터를 특정 프로퍼티만 올 수 있게 자동완성 잘됩니다.

  • 팔로워 confirm 되면 나의 follower 증가 + 상대방 followee 증가

  • 팔로워 삭제 되면 나의 follower 감소 + 상대방 followee 감소

await this.usersService.incrementFollowerCount(
  followerId,
  'followeeCount',
   1,
   qr,
);

userId가 오는 파라미터 자리에 user.id가 아닌 followerId가 들어간 이유는 followeeCount를 증가 해야 되기 때문이다. 즉, 팔로워를 수락 했으면 나의 followerCount를 증가 시키고 상대방 followeeCount를 증가 시켜야 되기 때문에, 삭제 했을때도 같은 원리

[결과]

2번 사용자가 1번 사용자를 팔로워하고, 1번 사용자가 팔로워를 수락 했을때

답변 1

답변을 작성해보세요.

1

안녕하세요!

열심히 하셨네요!

공유 감사합니다!

rhkdtjd_12님의 프로필

rhkdtjd_12

질문자

2024.01.31

재미있는 강의 만들어 주셔서 감사합니다. 덕분에 즐겁게 완강 했네요! 😃