본문 바로가기
게임서버-스파르타코딩NodeJs_7기/CH6 최종 프로젝트

서브 목록과 유저의 수행목록을 비교하여 해당 업적을 완료하였는지 확인하는 로직

by GREEN나무 2025. 3. 11.
728x90

업적

 ㄴ 서브업적(업적 상세목록)

 

유저의 완료 업적(업적C)

 ㄴ 수행한 세부 업적(업적 P)

 

 

// src\achievement-p\achievement-p.service.ts


    // 서브업적과 업적 진행상황을 비교하여 업적C 추가하기
    // 비교 방법
    // 1. 두 배열의 길이 비교(쉬움)
    // 2.  P 안에 subId가다 있는지 검증(정확)
    //      in 함수 사용
    //      includes()
    //      every()
    // javascript in?
    // 서브 배열(sub_id 모음)과 P배열(Pid 모음)의 길이가 같다
    // P배열(Pid 모음)안에 서브 배열(sub_id 모음)이 모두 존재한다
    // 두 조건을 만족한 경우 C에 추가

    // subAhcivment 배열 생성 (subAllByA 결과에서 id만 추출)
    const subAhcivment = (
      await this.repository.subAllByA(isSubId.achievement_id)
    ).map((subId) => subId.id);
    if (!subAhcivment || subAhcivment.length < 1) {
      console.log('s-서브목록조회실패');
      throw new BadRequestException('s-서브목록 조회실패했습니다.');
    }

    // ahcivmentP 배열 생성 (pAllByA 결과에서 sub_achievement_id만 추출)
    const ahcivmentP = (
      await this.repository.pAllByA(isSubId.achievement_id)
    ).map((subId) => subId.sub_achievement_id);
    if (!ahcivmentP || ahcivmentP.length < 1) {
      console.log('P-서브목록조회실패');
      throw new BadRequestException('P-서브목록 조회실패했습니다.');
    }
    // 길이 비교
    if (subAhcivment.length !== ahcivmentP.length) {
      console.log('길이가 다름');
    } else {
      // 모든 subAhcivment 값이 ahcivmentP에 포함되는지 확인
      const isMatching = subAhcivment.every((id) => ahcivmentP.includes(id));

      if (isMatching) {
        console.log('두 배열이 완전히 일치함');
        // 업적C 테이블에 해당 업적 추가
        try {
          const dataC = await this.repository.createC({
            user_id,
            achievement_id: isSubId.achievement_id,
          });
          const saveToC = await this.repository.saveC(dataC);
          console.log('업적C에 저장 : ', saveToC);
        } catch (error) {
          console.error(error);
        }
      } else {
        console.log('일치하지 않는 값이 있음');
      }
    }