All'alba vincerò

At dawn, I will win!

Javascript

[JS] crypto.randomUUID(): 고유한 식별자(UUID) 생성 메서드

나디아 Nadia 2024. 8. 25. 15:21

📌 crypto.randomUUID()

: JavaScript에서 고유한 식별자(UUID, Universally Unique Identifier)를 생성하는 메서드

  • crypto 모듈에서 제공되며, UUID v4 형식으로 랜덤하게 생성된 문자열을 반환하여 식별자로 사용한다.
  • 생성된 UUID는 128비트 길이의 8-4-4-4-12 형식의 32자리 16진수 문자열로 구성된다.
    ex) 123e4567-e89b-12d3-a456-426614174000
  • cryptographically secure(암호학적으로 안전한)한 방식으로 난수를 생성하여 고유성을 보장한다.
  • 사용하는 상황
    • 데이터베이스에서 각 레코드에 고유한 ID를 부여할 때 사용된다.
    • 파일 이름을 중복되지 않도록 고유하게 생성할 때 사용된다.
    • 세션 ID, 토큰 등을 생성할 때 사용된다.

 

 

✅ 사용

  • crypto.randomUUID()를 호출하여 식별자 (UUID) 생성
let uuid = self.crypto.randomUUID();

console.log(uuid); 
// "36b8f84d-df4e-4d49-b662-bcde71a8764f"

 

 

 

 

예제 1) 식별자 생성 & 부여 

function createUniqueID() {
  // 고유한 식별자를 생성해준다.
  const uniqueId = crypto.randomUUID();
  return uniqueId;
}

// 새 작업을 생성할 때 고유한 ID가 부여된다.
function createNewTask(title, description) {
  const newTask = {
    id: createUniqueID(), // 고유 ID가 생성된다.
    title: title,
    description: description,
    status: 'planned',
  };

  console.log('새로운 작업:', newTask);
}

createNewTask('테스트 작업', '작업에 대한 설명');

 

 

 

예제 2) 칸반 보드(kanban) 기능

  • 작업 생성, 작업 삭제
// 목록의 초기 상태(기본 목록)
const initialTasks = [
  {
    id: '6602c2fe-1cc6-4010-8cf6-e81f53b5eab2',
    title: 'Zustand로 관리하는 리액트 앱 상태',
    description: '컨텍스트 없이도 손쉽게 상태 공유 및 관리를 할 수 있어요.',
    status: TASKS.planned,
  },
];


// kanban 보드 기능
const store = (set) => ({
  tasks: initialTasks,
  draggedTask: null,

  // 작업 추가 메서드
  addTask: (title, description, status) =>
    set(
      (state) => ({
        tasks: [
          ...state.tasks,
          { id: crypto.randomUUID(), title, description, status },
          // crypto.randomUUID()를 사용하여 작업의 고유 ID를 생성
        ],
      }),
      false,
      'addTask'
    ),

  // 작업 삭제 메서드
  deleteTask: (id) =>
    set(
      (state) => ({
        tasks: state.tasks.filter((task) => task.id !== id),
        // crypto.randomUUID()에 의해 생성된 ID
        // filter 메서드를 사용하여 ID가 일치하지 않는 작업만 남기고 새로운 tasks 배열을 설정
      }),
      false,
      'deleteTask'
    )
});


const useKanbanBoardStore = create(devtools(store));

export default useKanbanBoardStore;

 

 


 

 

Crypto: randomUUID() method - Web APIs | MDN

The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.

developer.mozilla.org