[Node.JS] Troubleshooting issue: Redis사용 시, await setAsync(); 결과로 null이 나오는 이유?

박두팔이·2024년 3월 29일
0

Node.JS

목록 보기
18/20

나는 /upload로 라우터 요청이 들어오기 전에 인증되도록 설정해뒀다. 그렇기 때문에 캐시된 데이터가 있다면 router로 넘어가도록 아래와 같이 로직을 작성했다.

 // 캐시된 데이터가 있다면 router로 넘어가기
  if(cachedData) {
      return next();
  } else { // 캐시된 데이터가 없다면 DB에서 조회
      const result = await deviceRepository.findDeviceNameByOwnerId(req.headers.device_owner, req.headers.device_name, dbConnection);
      if (result.length > 0 && result[0].http_token == uuidToken) {
          logger.info(`Token validation successful for device owner: ${req.headers.device_owner} and device name: ${req.headers.device_name}`);
          // DB 조회 결과를 Redis에 저장
          await setAsync(cashedKey, 1800, JSON.stringify(result[0])); // 30분 동안 캐시 유지
          return next();
      } else {
          throw new Error('HTTP auth (token) error')
      }
  }
  • 하지만 이 코드에서 cachedData 결과는 null이다.
  • 따라서 else{}에서 캐시된 데이터가 없는 경우의 로직을 실행해야 하는데, await setAsync()함수에서 문제가 생겨 다음 라우터로 넘어가지 않는 것 같았다.
  • 아래와 같이 코드를 수정해주었다
    // 기존 코드
    await setAsync(cashedKey, 1800, JSON.stringify(result[0]));
    
    // 변경 후 코드
    await setAsync(cashedKey, JSON.stringify(result[0]), 'EX', 1800);
    • setAsync 함수에 전달하는 인자는 setAsync(key, value, 'EX', expiration)의 형태로 사용되어야 한다.
    • 하지만 기존의 코드에는 적절한 인자가 전달되지 않았다.
    • Redis의 SET 명령에 TTL(Time to Live)을 설정할 때는 마지막 두개의 인자로 EX와 만료 시간을 제공해야 한다.
    • 여기서, JSON.stringify(result[0]) 을 실행하면 나오는 결과를 살펴보자.
      • 예를 들어, result[0] 객체가 다음과 같다고 가정해보자.
        {
        	device_owner: 'owner123',
        	device_name: 'deviceABC',
        	http_token: 'uuidToken123'
        }
      • JSON.stringify(result[0])를 실행하면, 위 객체는 다음과 같은 JSON 문자열로 변환된다.
        "{\"device_owner\":\"owner123\",\"device_name\":\"deviceABC\",\"http_token\":\"uuidToken123\"}"
      • 이렇게 변환된 JSON문자열은 이제 Redis에 저장할 수 있는 형태가 되어 set명령을 통해 해당 문자열을 cashedKey의 value로 저장할 수 있게 되는 것이다.
      • 저장된 이 문자열은 getAsync를 통해 가져올 수 있다.
      • 이 문자열을 다시 javaScript 객체로 변환하는 방법은 JSON.parse()를 사용하면 가능하다.
      • 코드 수정 후→ 해결 완료!

결론: 문법문제..

profile
기억을 위한 기록 :>

0개의 댓글