[Restful] REST - UUID

Zero·2023년 3월 13일
0

REST

목록 보기
6/8

UUID

지난 포스팅에서 우리는 comment에 임의의 id를 부여했다. 이렇게 임의로 아이디를 부여하게 되면 별로 좋은 방법이 아니라는 것을 알 것이다. 이런 경우를 위해 사용하는 패키지 UUID를 사용해보도록 하자.

UUID는 유니크한 ID를 생성해주는 패키지라고 생각하면 된다. 설치는 다음과 같이 진행하자

npm i uuid


UUID 적용하기

const { v4 : uuid} = require('uuid');

const comments = [
  {
    id : uuid(),
    username : 'Todd',
    comment : 'lol that is so funny !'
  },
  {
    id : uuid(),
    username : 'Skyler',
    comment : 'I like to go birdwatching with my dog'
  },
  {
    id : uuid(),
    username : 'Sk8erBoi',
    comment : 'Plz delete your account, Todd'
  },
  {
    id : uuid(),
    username : 'onlysayswoof',
    comment : 'woof woof woof !!'
  }
]

app.post('/comments', (req,res) => {
  const {username, comment} = req.body;
  comments.push({id: uuid(), username, comment});
  res.redirect('/comments');
})

다음과 같이 v4를 uuid라는 이름의 변수로 전환해준뒤에 comment 내부의 id에 uuid()를 사용해주면 고유한 id를 부여해준다. 이전에 새로 등록하는 Post에 대해서도 고유 id를 부여할 수 있도록 id:uuid()를 추가하자.

--> 다음과 같이 해당 comment의 고유 id가 출력된다.

0개의 댓글