IndexedDB는 브라우저에 구조화된 데이터를 대량으로 저장하는 트랜잭션 기반 키-값 데이터베이스다. idb는 이벤트·콜백 방식인 네이티브 API(Application Programming Interface)를 Promise로 감싼 1KB 남짓의 얇은 래퍼다.
// 네이티브: request마다 onsuccess/onerror
const req = indexedDB.open('myDB', 1)
req.onsuccess = e => {
const tx = e.target.result.transaction('store', 'readonly')
tx.objectStore('store').get('key').onsuccess = ev => console.log(ev.target.result)
}
// idb: async/await
const db = await openDB('myDB', 1)
console.log(await db.get('store', 'key'))- idb는 단일 작업의 트랜잭션을 알아서 열어 주고(
db.get·put·delete), 에러를try/catch로 잡게 해 주며, 커서를for await로 돈다(idb/with-async-ittr로 import할 때). TypeScript 스키마 타입도 지원한다 - 의존성을 최소화해야 하거나 트랜잭션을 아주 세밀하게 다뤄야 하면 네이티브를 쓴다
- 문자열 몇 개를 저장하는 정도라면 동기 API인 localStorage가 더 간단하다. IndexedDB는 용량이 크거나 객체·Blob을 다룰 때 쓴다
- 오프라인 우선 앱(로컬 퍼스트 아키텍처)이나 Electron 렌더러의 로컬 저장소로도 쓰인다. Promise 동작은 Promise