LoginSignup
52
36

More than 5 years have passed since last update.

Dexie.jsでIndexedDBを使ってみる

Last updated at Posted at 2016-11-22

Dexie.jsでIndexedDBを使ってみる

IndexedDBに興味を持ったので使ってみようと思いましたが、素で使うのは大変そうなのでDexie.jsというライブラリを利用して、IndexedDBに少し触れてみたいと思います。
公式ドキュメントもあります。

今回はChomeの最新版で試してみます。

IndexedDBはqiita製のメモアプリ「Kobito」にも使用されているようです(多分)

DB定義

AppDatabaseがDB名になります

var db = new Dexie('AppDatabase');

ストア定義

ストアとは、平たく言えばテーブルみたいです。

db.version(1).stores({
  notes: "++id, title, body, *tags, updated_at"
});

今回は以下のようなストアとなります

ストア名 notes
主キー id
その他のキー title, body, tags, updated_at

キーには主キーやユニークキーを設定できます。

++ オートインクリメントな主キー
& ユニークキー
* 複数可(array)
[A+B] 複合index

DBの更新

ストアを更新したりストアの削除・追加をするには、古い定義を残したまま、新しい定義を追加していきます。その際にバージョンを1ずつ上げていくようです。

// バージョン1
db.version(1).stores({
  notes: "++id, title, body, *tags, updated_at"
});

// バージョン2 usersストアを追加
db.version(2).stores({
  notes: "++id, title, body, *tags, updated_at",
  users: "++id, name"
});

// バージョン3 notesストアにgoodを追加
// 更新時にtagsにgoodがあったら、新しく追加したキー「good」にtrueを入れるようにします。
db.version(3).stores({
  notes: "++id, title, body, *tags, good, updated_at",
  users: "++id, name"
}).upgrade(function() {
  return db.notes.modify(function(note) {
    if (note.tags.indexOf('good')) {
      note.good = true;
    }
  });
});

データ追加(add/bulkAdd)

db.notes.add({
  title: "タイトル",
  body: '本文',
  tags: ["IndexedDB", "Dexie.js"],
  updated_at: new Date()
});

データ更新(update)

var id = 1;
// id="1"では更新できませんでした。

db.notes.update(id, {
  body: '本文を更新',
  updated_at: new Date()
});

データ追加/更新(put/bulkPut)

データなければ追加、既にあれば更新となります

db.notes.put({
  id: 2,
  title: "タイトル",
  body: '本文',
  updated_at: new Date()
});

データ全件取得

db.notes
    .toArray()
    .then(function (notes) {
      console.log(notes);
    });

データ削除(delete/bulkDelete)

var id = 1;
db.notes.delete(id);

確認

「F12」でコンソールを開き、Applicationタブへ移動すると「Storage」一覧にIndexedDBという項目があるので、そこで中身が見れます。

Screenshot from 2016-11-22 17-48-48.png

まとめ

上記に載せた以外にも、トランザクションや条件検索などがあります。

シンプルで使いやすいです。

52
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
52
36