여느 때와 같이 MySQL과 Node를 쓰고 있었는데...
정말 갑자기 JSON에서 오류가 떴다.
값자기 value가 빈 문자열이 된 것.
..??????
정말 갑자기. 5초 전까지만 해도 잘만 돌아가던 함수가 갑자기 이상하다.
MySQL로 쿼리를 보내서, JSON 변환을 해서 아래와 같이 사용하고 있었다.
const queryResult = await connection.query(
`SELECT * FROM TABLE_A`);
const query = JSON.parse(JSON.stringify(queryResult))[0][0];
그러면 query라는 변수에
{
"key": "value"
}
이렇게 저장이 되어야 하는데, value가 그냥 ""으로 저장이 되는 것이었다.
진짜 당황스러운 경험이었다...
구글링을 좀 해보니 JSON.stringify() 쪽에 문제가 있는 것이라고 판단했다.
사실 잘 모르겠다. 이걸 뭐라고 구글링하지도 굉장히 고심했다.
수년간의 구글 노예 경험을 살려 최대한 살려 유추해본 결과다. 아닐 수도 있다.
찾다보니 JSON.stringify()가 속도나 성능 면에서 문제가 좀 있어서 다른 걸로 교체해야 한다는 글이 꽤 되었다.
그래서 그냥 겸사겸사 함수를 바꾸기로 했다.
우선 JSON.parse(JSON.stringify()) 이 함수를 쓰는 이유는, 값을 clone하기 위해서이다. (자세한 이유는 아래 stcak overflow 링크를 참고하거나 및 구글링 해보면 많이 나온다.)
근데 JSON.stringify()는 우선 Numbers, Strings, Booleans 값들만 사용 가능하다. 그 외의 값들은 그냥 자기가 알아서 처리해버린다(;;) 그리고 속도가 좀 느리다. 그 외 문제는 아래 참고를 확인해볼 것.
그래서 내가 택한 방식은 deep clone이다. 사용방법은 그냥 npm 같이 쓰면 된다.
1. lodash.clonedeepwithf 모듈 npm install
2. const cloneDeep = require('lodash.clonedeep'); 선언
3.
const queryResult = await connection.query(
`SELECT * FROM TABLE_A`);
const query = cloneDeep(queryResult);
이렇게 쓰면 끝!
뭐 다들 좋다는 데엔 이유가 있지 않을까 하고 써보는 중.
추후에 문제가 또 생기면 그때 추가 포스트를 해보겠습니다.
아래 참고 문서들은 꼭 읽어보길 추천합니다! 저도 지금까지 그냥 무지성으로 JSON.parse(JSON.stringify()) 썼는데 읽으니까 생각보다 심오한 뜻이 있었구나/.... 싶었습니다.
참고
https://stackoverflow.com/questions/24744474/json-parsejson-stringifyx-purpose
JSON.parse(JSON.stringify(x)) Purpose?
While I was working on a project, I came across this snippet of code: var params = JSON.parse(JSON.stringify(defaultParams)); Does this code actually do anything?
stackoverflow.com
[JavaScript] JSON.stringify가 빈 배열을 반환하는 경우 (JSON.stringify returns an empty array)
object에 이것저것 property를 실컷 세팅해놓고 JSON.stringify() 함수에 담갔다 뺐더니 빈 배열을 표시하는 문자열만 반환되는 허무한 경우가 있었다. // 최초 선언부분은 아직 비밀이다..; arr['name'] = '백
bloodguy.tistory.com
Why JSON.parse(JSON.stringify()) is a bad practice to clone an object in JavaScript
Cloning of objects often become a problem to JS programmers. Surprisingly, the second popular answer to a question `What is the most…
medium.com
https://www.samanthaming.com/tidbits/70-3-ways-to-clone-objects/
3 Ways to Clone Objects in JavaScript | SamanthaMing.com
Because objects in JavaScript are references values, you can't simply just copy using the =. Here are 3 ways for you to clone an object...
www.samanthaming.com
https://lodash.com/docs/4.17.15#cloneDeep
Lodash Documentation
_(value) source Creates a lodash object which wraps value to enable implicit method chain sequences. Methods that operate on and return arrays, collections, and functions can be chained together. Methods that retrieve a single value or may return a primiti
lodash.com
'Express' 카테고리의 다른 글
[Jest] Typescript + Express + Jest로 Controller 테스트하기 - Mock, Sequelize (0) | 2023.05.22 |
---|---|
[Jest] Typescript + Express + Jest로 Service 테스트하기 - Mock, Sequelize (0) | 2023.05.22 |