본문 바로가기

개발/JAVASCRIPT

[IndexedDB] 생소한 그 이름 파헤쳐 보자

728x90
반응형

팀에서 IndexedDB를 한 번 사용해보자는 이야기가 나왔다.

 

내게는 신기술로 느껴지는 만큼 기록을 남겨두지 않으면 분명 나는 까먹고 말 것이다.


그래서 IndexedDB가 뭐냐면

브라우저 개발자도구->응용프로그램->저장소

늘 무심하게도 지나쳤던 이 항목이다.


기존 DB들과는 구조도 조금 다르고

쿼리문(?)도 익숙하지 않으니

그냥 예제부터 보고 갑시다.

const dbName = "myDatabase";
const storeName = "Person";

const data = {
  "김창식": { age: "25", gender: "male" },
  "윤옥분": { age: "30", gender: "female" }
};

const request = indexedDB.open(dbName, 1);

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

  const objectStore = db.createObjectStore(storeName, { keyPath: "age" });
};

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

  const transaction = db.transaction(storeName, "readwrite");
  const objectStore = transaction.objectStore(storeName);

  Object.keys(data).forEach(function(key) {
    objectStore.put({ name: key, age: data[key].age, gender: data[key].gender });
  });

  transaction.oncomplete = function(event) {
    console.log("Data added successfully");
  };

  transaction.onerror = function(event) {
    console.log("Error while adding data");
  };
};

이런 식으로 코드를 짜면 

 

IndexedDB 항목 안에

myDatabase라는 데이터베이스가 생성되고

Person이라는 스토어가 생성된다

 

위 코드에서 각각

dbName의 값,

storeName의 값이 할당되었음을 알 수 있다.


자 그럼 Person 항목을 클릭해보자.

이제야 그나마 익숙한 key:value 형태의 모습이 나온다.

 

인덱스, 키, 값 형식으로 이루어져 있다.

 

여기서 주목해야 할 점은 키 항목이다.

키는 무조건 유일한 값의 속성이어야 한다.

 

여기서 중복되지 않은 키를 설정하려면 

두 가지 갈림길에 선다.

 

하나는,

keyPath를 임의의 값으로, autoIncrement를 true로 설정해서

키가 추가될때마다 1부터 1씩 증가하도록 설정하는 방법이다

{ keyPath: "id", autoIncrement: true }

 

나머지 하나는.

keyPath를 값 항목의 프로퍼티로 설정해주는 방법이다.

대신 이런 경우에는 유일한 값의 프로퍼티여야 한다(중복X)

예시 코드에서는 value의 프로퍼티인 age를 설정했다.

이렇게 되면 키는 age 프로퍼티의 값이 동적으로 할당된다.

{ keyPath: "age" }

버전이란

데이터베이스 항목을 보면 버전이라는 것이 있다.

좀 생소한 개념이라서 정리해두려고 한다.

 

const request = indexedDB.open(dbName, 1);

이 코드를 보면 숫자 1이 버전을 의미한다.

스키마가 변경될 때마다 버전을 +1 해줘야 한다.

 

쉽게 말해서

현재 스키마는 name, age, gender로 구성되어 있는데

 

city를 추가한다든지, phoneNumber를 추가한다든지 할 때에는 버전을 올려서 추가해야 한다.

되도록 이런 번거로움이 발생하지 않도록

미리 DB 구조를 잘 짜놓는 것도 좋겠다는 생각이 든다.


이제 CRUD를 해봅시다.

 

CREATE

request.onsuccess = function(event) {
  const db = event.target.result;
  const transaction = db.transaction(storeName, "readwrite");
  const objectStore = transaction.objectStore(storeName);

  objectStore.put({ name: "고구마", age: "27", gender: "female" });

  transaction.oncomplete = function(event) {
    console.log("Data added successfully");
  };

  transaction.onerror = function(event) {
    console.log("Error while adding data");
  };
};
//Create

 

이 코드를 실행하고

 

저장소의 새로고침을 누르면

다음과 같이 나온다


READ

request.onsuccess = function(event) {
  const db = event.target.result;
  const transaction = db.transaction(storeName, "readonly");
  const objectStore = transaction.objectStore(storeName);

  const request = objectStore.get("고구마");

  request.onerror = function(event) {
    console.log("Error while reading data");
  };

  request.onsuccess = function(event) {
    if (request.result) {
      console.log(request.result);
    } else {
      console.log("Data not found");
    }
  };
};
//Read

이 코드를 실행하면

 

콘솔에 잘 나온다


UPDATE

request.onsuccess = function(event) {
  const db = event.target.result;
  const transaction = db.transaction(storeName, "readwrite");
  const objectStore = transaction.objectStore(storeName);

  const request = objectStore.get("김창식");

  request.onerror = function(event) {
    console.log("Error while reading data");
  };

  request.onsuccess = function(event) {
    if (request.result) {
      const data = request.result;
      data.age = "31";
      objectStore.put({ name: "김창식", age: "65", gender: "female" });
    } else {
      console.log("Data not found");
    }
  };

  transaction.oncomplete = function(event) {
    console.log("Data updated successfully");
  };

  transaction.onerror = function(event) {
    console.log("Error while updating data");
  };
};
//Update

이 코드를 실행하고

저장소의 새로고침을 눌러주면

 

김창식씨가 65세 여성으로 변한 것을 확인할 수 있다.


DELETE

request.onsuccess = function(event) {
  const db = event.target.result;
  const transaction = db.transaction(storeName, "readwrite");
  const objectStore = transaction.objectStore(storeName);

  const request = objectStore.delete("윤옥분");

  request.onerror = function(event) {
    console.log("Error while deleting data");
  };

  request.onsuccess = function(event) {
    console.log("Data deleted successfully");
  };

  transaction.onerror = function(event) {
    console.log("Error while deleting data");
  };
};
//Delete

이 코드를 실행하고

저장소 새로고침하면

 

윤옥분씨는 사라졌다.

 

728x90
반응형