개발일지

개발일지 79일차

index.ys 2023. 6. 23. 15:23

MySQL NaN에러

  • 댕파인더 조회시 10개의 게시글을 조회하고 다음 요청시 다시 10개의 게시글을 조회하는 무한 스크롤 기능 구현중 오류발생

controller

  • 가져올 페이지 갯수를 쿼리스트링으로 입력받고 page변수에 할당함
  • offset 변수에 가져올 페이지 갯수를 할당함
getPosts = async (req, res) => {
    const limit = 10;
    const page = req.query.page
    const offset = (page - 1) * limit; // 페이지네이션
    const userId = res.locals.user ? res.locals.user.userId : null;
    const posts = await this.postService.getPosts(userId, limit, offset);
    return res.status(200).json({ lostPostsData: posts });
  };

service

getPosts = async (userId, limit, offset) => {
        try {
            if (!userId) {
                return await this.getAllPostsRecently(limit, offset);
            }

            const userLocation = await this.postRepository.findUserLocation(userId);
            if (userLocation === false) {
                return await this.getAllPostsRecently(limit, offset);
            }

            const findNearbyPosts = await this.postRepository.findNearbyPosts(userId, limit, offset);
            const results = await Promise.all(
                findNearbyPosts.map(async (item) => this.mapPost(item))
            )
            return results
        } catch (error) {
            error.failedApi = "댕파인더 조회"
            throw error
        }
    }

repository

    getPosts = async (limit, offset) => {
        return await this.postsModel.findAll({
            limit: limit,
            offset: offset,
            order: [
                ['createdAt', 'DESC']
            ],
        });
    }

에러코드

  • mysql에 접근할때 NaN 에러 발생
RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: Undeclared variable: NaN

문제점

  • page변수에 number가 아닌 string타입의 데이터가 선언되어 있음
  • offset 변수에서 ( page - 1 ) 연산을 수행할때 page변수는 string 타입이지만 빼기 연산자의 속성때문에 string 타입도 연산을 수행함
  • page 변수에는 여전히 string 타입이 저장되어 있어 mysql에 접근할때 number가 아닌 string 타입으로 접근함
getPosts = async (req, res) => {
    const limit = 10;
    const page = req.query.page
    const offset = (page - 1) * limit; // 페이지네이션
    const userId = res.locals.user ? res.locals.user.userId : null;
    const posts = await this.postService.getPosts(userId, limit, offset);
    return res.status(200).json({ lostPostsData: posts });
  };

해결방법

  • page변수를 number로 변경
 const page = Number(req.query.page)