23.6 username/tags로 포스트 필터링하기

    이번에는 특정 사용자가 작성한 포스트만 조회하거나 특정 태그가 있는 포스트만 조회하는 기능을 만들어 보겠습니다.

    먼저 조금 전에 새로 만든 계정으로 포스트를 작성합니다. GET /api/posts에 요청을 해서 두 명의 사용자가 쓴 포스트가 있는지 확인한 다음, 포스트 목록 조회 API를 다음과 같이 수정해 보세요.

    src/api/posts/posts.ctrl.js - list

    /*
      GET /api/posts?username=&tag=&page=
    */
    export const list = async ctx => {
      // query는 문자열이기 때문에 숫자로 변환해 주어야 합니다.
      // 값이 주어지지 않았다면 1을 기본으로 사용합니다.
      const page = parseInt(ctx.query.page || '1', 10);
    
      if (page < 1) {
        ctx.status = 400;
        return;
      }
    
      const { tag, username } = ctx.query;
      // tag, username 값이 유효하면 객체 안에 넣고, 그렇지 않으면 넣지 않음
      const query = {
        ...(username ? { 'user.username': username } : {}),
        ...(tag ? { tags: tag } : {}),
      };
    
      try {
        const posts = await Post.find(query)
          .sort({ _id: -1 })
          .limit(10)
          .skip((page - 1) * 10)
          .lean()
          .exec();
        const postCount = await Post.countDocuments(query).exec();
        ctx.set('Last-Page', Math.ceil(postCount / 10));
        ctx.body = posts.map(post => ({
          ...post,
          body:
            post.body.length < 200 ? post.body : `${post.body.slice(0, 200)}...`,
        }));
      } catch (e) {
        ctx.throw(500, e);
      }
    };

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.