2018/05/19 #jsfes @himanoa
https://caniuse.com/#feat=indexeddb
InxededDB | LocalStorage | |
---|---|---|
容量制限 | 50MB(無制限) | 最大10MB |
Index | 自動採番 複合キー等 |
保存時に使うキーのみ |
同期 / 非同期 | 非同期 | 同期 |
let db = indexedDB.open('HimanoaDB', 1);
let result
req.onsuccess = function (evt) {
db = db.result;
};
req.onerror = function (evt) {
console.error("openDb:", evt.target.errorCode);
};
req.onupgradeneeded = function (evt) {
const store = evt.currentTarget.result.createObjectStore(
'articles', { keyPath: 'id', autoIncrement: true });
store.createIndex("body", "body", { unique: false })
store.createIndex("author", "author", { unique: false })
store.transaction.oncomplete = function(event) {
const customerObjectStore = db.transaction("articles", "readwrite")
.objectStore("articles");
customerObjectStore.add({ title: "タイトル",
body: "読者じゃぶじゃぶ課金したくなるような射幸心を煽りまくる説明文章"
});
};
};
const db = new Dexie('HimanoDB');
db.version(1).stores({
// ++ はオートインクリメントされるキー
articles: '++id, title, body'
});
db.open();
// ES2017 ~
await db.articles.add({ title: "title", body: "body" });
db.version(1).stores({
articles: "++id,title,body"
});
db.version(2).stores({
artcles: "++id,title,body,summary"
}).upgrade (function (trans) {
trans.articles.toCollection().modify (function (article) {
article.summary = 'No summary'
});
});
Node環境にはindexedDBの実装が存在しない
$ node
> indexedDB
undefined
>
global.indexedDB =
require("fake-indexeddb");
global.IDBCursor =
require("fake-indexeddb/lib/FDBCursor");
global.IDBCursorWithValue =
require("fake-indexeddb/lib/FDBCursorWithValue");
global.IDBDatabase =
require("fake-indexeddb/lib/FDBDatabase");
global.IDBFactory =
require("fake-indexeddb/lib/FDBFactory");
global.IDBIndex =
require("fake-indexeddb/lib/FDBIndex");
global.IDBKeyRange =
require("fake-indexeddb/lib/FDBKeyRange");
global.IDBObjectStore =
require("fake-indexeddb/lib/FDBObjectStore");
global.IDBOpenDBRequest =
require("fake-indexeddb/lib/FDBOpenDBRequest");
global.IDBRequest =
require("fake-indexeddb/lib/FDBRequest");
global.IDBTransaction =
require("fake-indexeddb/lib/FDBTransaction");
global.IDBVersionChangeEvent =
require("fake-indexeddb/lib/FDBVersionChangeEvent");
JestだとGlobalSetupで実行できるようにする
https://gist.github.com/himanoa/e8a143c19606633a79db7d0fd28d25f7