최신 웹 애플리케이션, 특히 프로그레시브 웹 앱(PWA)을 구축할 때 데이터를 오프라인으로 저장할 수 있는 방법을 갖추는 것이 중요합니다. IndexedDB는 사용자가 오프라인일 때에도 웹 앱이 데이터를 저장하고 검색할 수 있게 해주는 강력한 클라이언트 측 데이터베이스입니다. 이 가이드는 IndexedDB의 기본 사항을 안내하며 웹 앱 내에서 데이터를 생성, 읽기, 업데이트 및 삭제(CRUD 작업)하는 방법을 보여줍니다.
IndexedDB는 파일 및 Blob을 포함하여 대량의 구조화된 데이터를 클라이언트 측에 저장하기 위한 하위 수준 API입니다. localStorage와 달리 IndexedDB를 사용하면 문자열뿐만 아니라 복잡한 데이터 유형을 저장할 수 있습니다. 비동기식 트랜잭션 데이터베이스 모델을 사용하므로 대규모 데이터 세트 또는 오프라인 데이터 동기화를 처리해야 하는 애플리케이션에 강력합니다.
IndexedDB 작업의 핵심 단계를 살펴보겠습니다. 우리는 다음을 다룰 것입니다:
IndexedDB와 상호작용하려면 먼저 데이터베이스에 대한 연결을 열어야 합니다. 데이터베이스가 존재하지 않으면 생성됩니다.
const request = indexedDB.open('MyCustomersDatabase', 1); request.onerror = (event) => { console.error('Database error:', event.target.errorCode); }; request.onsuccess = (event) => { const db = event.target.result; console.log('Database opened successfully', db); }; request.onupgradeneeded = (event) => { const db = event.target.result; if (!db.objectStoreNames.contains('customers')) { const objectStore = db.createObjectStore('customers', { keyPath: 'id' }); objectStore.createIndex('name', 'name', { unique: false }); objectStore.createIndex('email', 'email', { unique: true }); console.log('Object store created.'); } };
현재 상황은 다음과 같습니다.
이제 데이터베이스와 객체 저장소가 설정되었으므로 여기에 데이터를 추가해 보겠습니다.
const addCustomer = (db, customer) => { const transaction = db.transaction(['customers'], 'readwrite'); const objectStore = transaction.objectStore('customers'); const request = objectStore.add(customer); request.onsuccess = () => { console.log('Customer added:', customer); }; request.onerror = (event) => { console.error('Error adding customer:', event.target.errorCode); }; } const customer = { id: 1, name: 'John Doe', email: '[email protected]' }; request.onsuccess = (event) => { const db = event.target.result; addCustomer(db, customer); };
현재 상황은 다음과 같습니다.
IndexedDB에서 데이터를 읽는 것도 간단합니다. get() 메소드를 사용하여 방금 추가한 고객을 검색해 보겠습니다.
const getCustomer = (db, id) => { const transaction = db.transaction(['customers'], 'readonly'); const objectStore = transaction.objectStore('customers'); const request = objectStore.get(id); request.onsuccess = (event) => { const customer = event.target.result; if (customer) { console.log('Customer found:', customer); } else { console.log('Customer not found.'); } }; request.onerror = (event) => { console.error('Error fetching customer:', event.target.errorCode); }; } request.onsuccess = (event) => { const db = event.target.result; getCustomer(db, 1); // Fetch customer with ID 1 };
기존 레코드를 업데이트하려면 add()와 유사하게 작동하지만 키가 이미 존재하는 경우 레코드를 바꾸는 put() 메서드를 사용할 수 있습니다.
const updateCustomer = (db, customer) => { const transaction = db.transaction(['customers'], 'readwrite'); const objectStore = transaction.objectStore('customers'); const request = objectStore.put(customer); request.onsuccess = () => { console.log('Customer updated:', customer); }; request.onerror = (event) => { console.error('Error updating customer:', event.target.errorCode); }; } const updatedCustomer = { id: 1, name: 'Jane Doe', email: '[email protected]' }; request.onsuccess = (event) => { const db = event.target.result; updateCustomer(db, updatedCustomer); };
마지막으로 레코드를 삭제하려면 delete() 메서드를 사용하세요.
const deleteCustomer = (db, id) => { const transaction = db.transaction(['customers'], 'readwrite'); const objectStore = transaction.objectStore('customers'); const request = objectStore.delete(id); request.onsuccess = () => { console.log('Customer deleted.'); }; request.onerror = (event) => { console.error('Error deleting customer:', event.target.errorCode); }; } request.onsuccess = (event) => { const db = event.target.result; deleteCustomer(db, 1); // Delete customer with ID 1 };
IndexedDB는 특히 오프라인 우선 웹 앱에서 클라이언트 측 데이터 저장소를 처리하기 위한 강력한 솔루션입니다. 이 가이드를 따라 다음 방법을 배웠습니다.
IndexedDB를 사용하면 데이터를 로컬에 저장하고 인터넷 연결 없이도 작동하는 보다 탄력적인 웹 애플리케이션을 구축할 수 있습니다.
MDN 웹 문서 - IndexedDB API
IndexedDB의 작동 방식, API 방법, 사용 사례에 대한 종합 가이드입니다.
MDN IndexedDB 가이드
Google 개발자 - IndexedDB
오프라인 지원 웹 앱 구축을 위한 모범 사례 및 IndexedDB 사용을 다루는 자세한 문서입니다.
Google 개발자 - IndexedDB
W3C 색인화된 데이터베이스 API
IndexedDB의 기술 구현 및 구조를 설명하는 W3C의 공식 사양입니다.
W3C IndexedDB 사양
이 튜토리얼을 넘어 IndexedDB에 대해 더 자세히 알아보고 싶다면 이 리소스는 추가적인 깊이와 맥락을 제공할 것입니다!
즐거운 코딩하세요!
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3