728x90
반응형

1. 문제

북마크에서 기본으로 제공하는 기본 북마크에 포스트를 저장하는 기능


2. 시도해본 것들

우선 기본 북마크는 어떻게 찾을 것인가?

회원가입하자마자 모두에게 주어지는 기본 북마크이므로

제일 먼저 생성된 북마크이다.


3. 해결과정

findOne 메서드로 찾으면 가장 먼저 나오는 것이 기본 북마크였다.

 

/*
        ### 23.03.28
        ### 표정훈
        ### 기본 북마크에 포스팅 더하기
        */
  async basicCollectionPlusPosting(postId: number, userId: number) {
    try {
      //본인의 첫번째 북마크(모든 게시물)의 id를 찾는다.
      const basicBookmark = await this.collectionRepository.findOne({
        where: {
          user_id: userId,
        },
        select: {
          id: true,
        },
      });

      const existingItem = await this.collectionItemRepository.findOne({
        where: {
          post: { id: postId },
          collection: { id: basicBookmark.id }, // 기본 북마크의 ID를 사용하여 조건문을 지정
        },
      });

      if (existingItem) {
        return; // 이미 있다면 종료
      }

      const collectionItem = this.collectionItemRepository.create({
        post: { id: postId },
        collection: { id: basicBookmark.id }, // 기본 북마크의 ID를 사용하여 컬렉션 아이템을 생성
      });

      await this.collectionItemRepository.save(collectionItem);
      return collectionItem;
    }

 

4. 알게 된 점

막연하게 기본 북마크는 어떤 방법으로 찾을 수 있을까 생각했는데

알고리즘 문제처럼 어떠한 방식으로 접근할 수 있을까 생각하다보면 쉽게 접근 할 수 있는 문제였다.

 

 

728x90
반응형
728x90
반응형

1. 문제

회원정지시 3일,7일,30일로 하려고 할때, 자동화하여

정지 풀어주는 로직을 고민하고 있었다.


2. 시도해본 것들

처음에는 타이머를 생각했으나, 서버가 꺼지면 자동으로 초기화되는 등

실제 서비스 제공하기는 어렵다.


3. 해결과정

타이머의 대체제를 찾던 도중 'node-cron'이라는 기능을 알게 되었다.

실제 서비스에서도 사용할 수 있고, 사용하는 방법도 간단했다.

 

4. 알게 된 점

타이머와 node-corn의 차이점을 알게 되었고,

corn의 경우, 서비스 코드에서 작성하는것이 아니라

app.module.ts 또는 main.ts 같은 곳에 작성해야 서비스가 사용될때마다 주기적으로

이벤트를 줘서 작동시킬 수 있다.

 

import * as cron from 'node-cron';
import { AdminModule } from './apis/administrator/admin.module';
import { AdminService } from './apis/administrator/admin.service';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    TypeOrmModule.forRootAsync({
      useClass: TypeOrmConfigService,
    }),

    AuthModule,

  ],
})
export class AppModule implements OnModuleInit {
  constructor(private adminService: AdminService) {}
  onModuleInit() {
    cron.schedule('* * * * *', async () => {
      await this.adminService.liftBanOnExpiredUsers();
    });
  }
}
728x90
반응형
728x90
반응형

이번 주 알게 된 점

금요일에 작성한 TIL의 내용으로

TypeORM으로는 복잡한 쿼리문을 작성하기 어려웠다.

TypeORM 쿼리빌더를 사용하니 손쉽게 해결했다.

효율성을 생각하니 쿼리빌더를 열심히 공부해야겠다는 생각이 들었다.

 

이번주 목표 달성 여부

북마크 세부기능 모두 완성

마이리스트 세부기능 모두 완성

 

다음주 목표 세우기

최종프로젝트 발표 준비

728x90
반응형
728x90
반응형

기존에 뜨는 맛집리스트라는 기능구현을 했다.

TypeORM으로 기능 구현했는데 그룹화하고, 평균값 구하는 등 많은 일을 하려다보니

find문을 사용한후로 다양한 로직을 구현했다.

 /*
    ### 23.03.20
    ### 표정훈
    ### [Main] 요즘 뜨는 맛집리스트🔥
    */
  async HotMyList() {
    try {
      // 1달 전 날짜를 구한다
      const oneMonthAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);

      // 컬렉션과 게시물, 좋아요 정보를 가져온다
      const myListSumLikes = await this.collectionItemRepository.find({
        relations: {
          post: {
            postLikes: true,
            user: true,
            images: true,
          },
          collection: {
            user: true,
          },
        },
        where: {
          // 컬렉션 타입이 myList 이면서 삭제되지 않은 것을 가져온다
          collection: {
            type: 'myList',
            deletedAt: null,
          },
          post: {
            // 좋아요가 삭제되지 않았고, 1달 이내에 좋아요 업데이트된 게시물만 가져온다
            postLikes: {
              deleted_at: null,
              updated_at: MoreThan(oneMonthAgo),
            },
          },
        },
        select: {
          id: true,
          post: {
            id: true,
            images: { id: true, file_url: true },
            postLikes: {
              id: true,
            },
            user: {
              id: true,
              nickname: true,
            },
          },
          collection: {
            id: true,
            name: true,
            user: {
              id: true,
              nickname: true,
            },
          },
        },
        take: 2,
      });

      // 컬렉션별 좋아요 수를 합산하여 그룹화한다
      const groupedData = myListSumLikes.reduce((groups: any, item: any) => {
        const collectionId = item.collection.id;
        if (!groups[collectionId]) {
          groups[collectionId] = {
            collection: item.collection,
            user: item.collection.user,
            sumLikes: 0,
          };
        }
        groups[collectionId].sumLikes += item.post?.postLikes?.length ?? 0;

        // 게시물에 포함된 이미지 URL 정보를 가져온다
        const images = item.post?.images ?? [];
        const fileUrls = images.map((image: any) => image.file_url);
        groups[collectionId].images = fileUrls;

        return groups;
      }, {});

      // 컬렉션별 좋아요 합산값에 따라 내림차순으로 정렬한다
      const collectionSumLikes: any = Object.values(groupedData);
      collectionSumLikes.sort((a: any, b: any) => b.sumLikes - a.sumLikes);

      // 상위 10개 컬렉션 정보를 구성하여 반환한다
      const top3Collections = collectionSumLikes
        // .slice(0, 10)
        .map(({ collection, user, sumLikes, images }: any) => {
          return {
            id: collection.id,
            name: collection.name,
            user: {
              id: user.id,
              nickname: user.nickname,
            },
            sumLikes,
            images,
          };
        });

      return top3Collections;
    }

그런데 위의 코드는 문제가 있었다. 정보를 가져올때 이미 take로 한정지어서 가져왔기에

뒤에 코드에서 몇개를 분리하든 의미가 없던 것이었다.

결국 쿼리빌더로 작성해봤는데 코드의 양이 엄청나게 줄어들었다.

 

/*
    ### 23.03.20
    ### 표정훈
    ### [Main] 요즘 뜨는 맛집리스트🔥
    */
  async HotMyList() {
    try {
      // 1달 전 날짜를 구한다
      const oneMonthAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);

      // 컬렉션별로 포스트의 좋아요를 모두 합쳐서 가장 좋아요수가 많은 컬렉션 5개를 순서대로 가져온다
      const top5Collections = await this.collectionItemRepository
        .createQueryBuilder('collectionItem')
        .leftJoinAndSelect('collectionItem.collection', 'collection')
        .leftJoinAndSelect('collection.user', 'user')
        .leftJoinAndSelect('collectionItem.post', 'post')
        .leftJoinAndSelect('post.postLikes', 'postLikes')
        .where('collection.type = :type', { type: 'myList' })
        .andWhere('postLikes.updated_at > :oneMonthAgo', { oneMonthAgo })
        .select([
          'collection.id',
          'collection.name',
          'user.id',
          'user.nickname',
          'user.profile_image',
          'COUNT(postLikes.id) as sumLikes',
        ])
        .groupBy('collection.id')
        .orderBy('sumLikes', 'DESC')
        .limit(5)
        .getRawMany();

      // 상위 5개 컬렉션 정보를 구성하여 반환한다
      const topCollections = top5Collections.map((item: any) => {
        return {
          id: item.collection_id,
          name: item.collection_name,
          user: {
            id: item.user_id,
            nickname: item.user_nickname,
            profile_image: item.user_profile_image,
          },
          sumLikes: item.sumLikes,
        };
      });

      return topCollections;
    }

TypeORM으로만 작성해왔는데

TypeORM 쿼리빌더가 복잡한 로직에는 훨씬 유용한것 같다.

따로 쿼리빌더를 공부해야겠다는 생각이 들었다.

 

 

728x90
반응형
728x90
반응형
  1. 요즘 뜨는맛집 - 유저프로필이미지가 없다 => post에 있는 user 정보가 아니라 collection에 있는 user정보였다.
  2. 요즘 뜨는맛집 - 리스트 5개 나오게 하기 => take 수량변경
  3. 맛집리스트 수정에서 이미지가 안된다 => 참고해야할 변수명이 image가 아닌 file 이었다.
  4. 맛집리스트 상세보기 - 카테고리 그룹네임-> 카테고리 네임 변경

프론트 연결중에 문제가 생긴 부분을 수정했고,

내일 배포할때 사용할 구글폼을 팀원들과 함께 작성하였다.

테스트코드 공부를 좀 하였으나 역시나 어려워서 머리가 아픈 하루였다.

728x90
반응형
728x90
반응형

컬렉션 안에 있는 맛집별로 평균 평점을 구하는 작업을 했다.

처음엔 아무 생각없이 모든 평점을 모아서 평균을 냈는데, 생각해보니

1가지 맛집에 대한 평점만 낸것이어서, 다른 맛집도 추가하여 분리해보았다.

 

맛집ID가 같은 것끼리 분리해야하니, 그룹화가 필요했고,

그룹화 이후 각 포스트 정보는 1개씩만 대표로 가져오게 했다.

 

  async getMyListDetail(collectionId: number, page: string) {
    try {
      let pageNum = Number(page) - 1;
      const myListInOnePage = 1;

      if (isNaN(pageNum) || pageNum < 0) {
        pageNum = 0;
      }

      // 컬렉션 이름과 포스트 정보 가져오기
      const myList = await this.collectionRepository.find({
        relations: {
          collectionItems: {
            post: { images: true, restaurant: true },
          },
        },
        where: {
          id: collectionId,
          // user_id: userId,
          deletedAt: null,
          type: 'myList',
        },
        select: {
          id: true,
          name: true,
          description: true,
          visibility: true,
          collectionItems: {
            id: true,
            post: {
              id: true,
              content: true,
              rating: true,
              images: true,
              restaurant: {
                id: true,
                x: true,
                y: true,
                place_name: true,
                category_group_name: true,
              },
            },
          },
        },
        skip: pageNum * myListInOnePage,
        take: myListInOnePage,
      });

      const [myListDetail] = myList.map((myList) => {
        const groupedPosts = {};
        for (const item of myList.collectionItems) {
          
          const restaurantId = item.post.restaurant.id;
          if (!groupedPosts[restaurantId]) {
            groupedPosts[restaurantId] = { posts: [], sum: 0, count: 0 };
          }
          groupedPosts[restaurantId].posts.push({
            ...item.post,
            restaurant: item.post.restaurant,
            images: item.post.images,
          });
          
          const rating = item.post.rating;
          if (typeof rating === 'number') {
            groupedPosts[restaurantId].sum += rating;
            groupedPosts[restaurantId].count++;
          }
        }

        
        const formattedPosts = [];
        for (const groupId in groupedPosts) {
          const group = groupedPosts[groupId];
          const avgRating =
            group.count > 0 ? (group.sum / group.count).toFixed(1) : null;

          if (group.posts.length > 0) {
            formattedPosts.push({
              id: group.posts[0].id,
              content: group.posts[0].content,
              rating: group.posts[0].rating,
              AvgRating: avgRating,
              images: group.posts[0].images,
              restaurant: group.posts[0].restaurant,
            });
          }
        }

        return {
          id: myList.id,
          name: myList.name,
          description: myList.description,
          visibility: myList.visibility,
          post: formattedPosts,
        };
      });

      return myListDetail;
    } catch (err) {
      console.error(err);
      throw new InternalServerErrorException(
        'Something went wrong while processing your request. Please try again later.',
      );
    }
  }
728x90
반응형
728x90
반응형

요즘 뜨는 맛집리스트와 내 친구의 맛집리스트 기능구현을 했다.

 

요즘 뜨는 맛집리스트는 쿼리문을 작성하는 것까진 쉬웠으나 원하는 값을 뽑아오는건 힘들었다.

추가적으로 내 친구의 맛집리스트는 어떤식으로 데이터를 가져올지 고민을 했다.

 

우선 user에서 정보를 가져와야 할 것 같았다.

내 userId를 통해 내가 팔로잉하고 있는 유저아이디를 찾았다.

해당 유저아이디를 where에 넣어서 유저게시물 정보를 찾아오는 방식으로 구현했다.

(유저아이디 먼저 찾고, 유저아이디를 토대로 게시물 정보 찾기)

 

const followerId = await this.followRepository.find({
        where: {
          follower: { id: userId },
        },
        select: {
          following: { id: true },
        },
        relations: {
          following: true,
        },
      });

      const followingIds = followerId
        .map((f) => f.following.id)
        .filter((id) => !isNaN(id));

      const myListFollwers = await this.collectionItemRepository.find({
        relations: {
          post: {
            user: true,
            images: true,
          },
          collection: {
            user: true,
          },
        },
        where: {
          collection: {
            type: 'myList',
            deletedAt: null,
            user_id: In(followingIds), //팔로워들의 아이디
          },
        },
        select: {
          post: {
            id: true,
            images: { id: true, file_url: true },
            user: {
              id: true,
              nickname: true,
            },
          },
          collection: {
            id: true,
            name: true,
            user: {
              id: true,
              nickname: true,
            },
          },
        },
      });

 

 

 

728x90
반응형
728x90
반응형

이번 주 알게 된 점

백앤드는 쿼리문에 익숙해지는게 매우 중요하다.

그리고 결과값을 받기 위해선 map에 익숙해져야 한다.

const myListSumLikes = await this.collectionItemRepository.find({
        relations: {
          post: {
            postLikes: true,
            user: true,
            images: true,
          },
          collection: {
            user: true,
          },
        },
        where: {
          // 컬렉션 타입이 myList 이면서 삭제되지 않은 것을 가져온다
          collection: {
            type: 'myList',
            deletedAt: null,
          },
          post: {
            // 좋아요가 삭제되지 않았고, 1달 이내에 좋아요 업데이트된 게시물만 가져온다
            postLikes: {
              deleted_at: null,
              updated_at: MoreThan(oneMonthAgo),
            },
          },
        },
        select: {
          id: true,
          post: {
            id: true,
            images: { id: true, file_url: true },
            postLikes: {
              id: true,
            },
            user: {
              id: true,
              nickname: true,
            },
          },
          collection: {
            id: true,
            name: true,
          },
        },
      });

내가 이런 쿼리문을 쉽게 작성할 날이 올줄이야.

너무 만족스럽다. 이제 쿼리문을 찾은 정보를 예쁘게 골라서 전달하기 위해

map함수에 익숙해지는것만 남았다.

 

이번주 목표 달성 여부

마이리스트 세부기능 모두 완성

 

다음주 목표 세우기

북마크 세부기능 모두 완성

728x90
반응형

+ Recent posts