how to use indexeddb

IndexedDB: 웹 브라우저 내의 데이터베이스

IndexedDB는 웹 브라우저에서 구조화된 데이터를 저장하고 검색할 수 있는 웹 표준 데이터베이스입니다. 이 포스팅에서는 IndexedDB를 사용하는 방법에 대해 알아보겠습니다.

IndexedDB 객체 생성

IndexedDB에 접근하기 위해 먼저 indexedDB 객체를 생성해야 합니다.

“`javascript
const request = indexedDB.open(“myDatabase”, 1); // “myDatabase”는 데이터베이스 이름, 1은 버전 번호

request.onupgradeneeded = function(event) {
const db = event.target.result;

const store = db.createObjectStore(“myStore”, { keyPath: “id” }); // “myStore”는 객체 저장소의 이름, “id”는 키 경로

store.createIndex(“nameIndex”, “name”, { unique: false }); // “nameIndex”는 인덱스의 이름, “name”은 인덱스 대상 속성
};

request.onsuccess = function(event) {
const db = event.target.result;

// 데이터베이스 작업 수행
};

request.onerror = function(event) {
console.log(“데이터베이스 열기 오류:”, event.target.errorCode);
};
“`

데이터 추가

IndexedDB에 데이터를 추가하려면 트랜잭션을 생성하고 해당 트랜잭션을 사용하여 객체 저장소에 데이터를 추가해야 합니다.

“`javascript
const transaction = db.transaction([“myStore”], “readwrite”); // “myStore”는 데이터를 저장할 객체 저장소의 이름
const store = transaction.objectStore(“myStore”);

const data = { id: 1, name: “John Doe”, email: “johndoe@example.com” };

const request = store.add(data);

request.onsuccess = function(event) {
console.log(“데이터가 성공적으로 추가되었습니다.”);
};

request.onerror = function(event) {
console.log(“데이터 추가 오류:”, event.target.errorCode);
};
“`

데이터 검색

IndexedDB에서는 객체 저장소에 저장된 데이터를 인덱스를 통해 검색할 수 있습니다. 예를 들어, nameIndex라는 인덱스를 사용하여 이름으로 데이터를 검색하는 방법은 다음과 같습니다.

“`javascript
const transaction = db.transaction([“myStore”], “readonly”); // 읽기 전용 트랜잭션 생성
const store = transaction.objectStore(“myStore”);

const index = store.index(“nameIndex”); // 인덱스 사용

const request = index.get(“John Doe”); // “John Doe” 이름으로 데이터 검색

request.onsuccess = function(event) {
const data = event.target.result;

if (data) {
console.log(“검색 결과:”, data);
} else {
console.log(“해당 데이터를 찾을 수 없습니다.”);
}
};

request.onerror = function(event) {
console.log(“데이터 검색 오류:”, event.target.errorCode);
};
“`

데이터 삭제

IndexedDB에서 데이터를 삭제하려면 해당 데이터의 키 값을 이용하여 삭제해야 합니다.

“`javascript
const transaction = db.transaction([“myStore”], “readwrite”);
const store = transaction.objectStore(“myStore”);

const request = store.delete(1); // 키 값이 1인 데이터 삭제

request.onsuccess = function(event) {
console.log(“데이터가 성공적으로 삭제되었습니다.”);
};

request.onerror = function(event) {
console.log(“데이터 삭제 오류:”, event.target.errorCode);
};
“`

데이터 업데이트

IndexedDB에서 데이터를 업데이트하려면 해당 데이터의 키 값을 이용하여 업데이트해야 합니다. 업데이트를 위해선 먼저 데이터를 삭제하고 다시 추가하는 방식을 사용합니다.

“`javascript
const transaction = db.transaction([“myStore”], “readwrite”);
const store = transaction.objectStore(“myStore”);

const newData = { id: 1, name: “Jane Doe”, email: “janedoe@example.com” };

const deleteRequest = store.delete(newData.id); // 키 값이 newData.id인 데이터 삭제

deleteRequest.onsuccess = function(event) {
const addRequest = store.add(newData); // 업데이트된 데이터 추가
addRequest.onsuccess = function(event) {
console.log(“데이터가 성공적으로 업데이트되었습니다.”);
};
addRequest.onerror = function(event) {
console.log(“데이터 업데이트 오류:”, event.target.errorCode);
};
};

deleteRequest.onerror = function(event) {
console.log(“데이터 삭제 오류:”, event.target.errorCode);
};
“`

IndexedDB를 사용하여 웹 애플리케이션에서 구조화된 데이터를 저장, 검색, 업데이트, 삭제하는 방법에 대해 알아보았습니다. IndexedDB는 대량의 데이터를 효과적으로 처리하고 오프라인 작업을 지원하는 데 효과적인 방법입니다. 더 자세한 정보는 공식 문서를 참조하시기 바랍니다.