JsStore - IndexedDBを使いやすくするO/Rマッパー風ライブラリ
HTML5でWebブラウザ内にデータを残す方法としてlocalStorageが有名ですが、他にIndexedDBがあります。しかしIndexedDBは検索できるKVSであったり、localStorageと違って非同期で使う、スキーマが必要など何かと面倒なイメージがあります。 そこで使ってみたいのがJsStoreです。IndexedDBをまるでデータベースのように使えるようにするソフトウェアです。
JsStoreの使い方
IndexedDBを開く処理です。スキーマの定義も行います。
var dbName ='JsStore_Demo';
function getDbSchema() {
var tblProduct = {
name: 'Product',
columns: [
{
name: 'Id',
primaryKey: true,
autoIncrement: true
},
{
name: 'ItemName',
notNull: true,
dataType: JsStore.DATA_TYPE.String
},
{
name: 'Price',
notNull: true,
dataType: JsStore.DATA_TYPE.Number
},
{
name: 'Quantity',
notNull: true,
dataType: JsStore.DATA_TYPE.Number
}
]
};
var db = {
name: dbName,
tables: [tblProduct]
}
return db;
}
データを登録する処理です。SQLと同じ、とは言いませんがO/Rマッパーのように使えます。
var value = {
column1: value1,
column2: value2,
column3: value3,
...
columnN: valueN
};
connection.insert({
into: "TABLE_NAME",
values: [Value], //you can insert multiple values at a time
}).then(function(rowsInserted) {
if (rowsInserted > 0) {
alert('Successfully Added');
}
}).catch(function(error) {
alert(error.message);
});
データの選択です。こちらもO/Rマッパー風です。もちろん条件指定もできます。
connection.select({
from: "Table_Name"
}).then(function(results) {
//results will be array of objects.
console.log(results);
}).catch(function(error) {
alert(error.message);
});
更新や削除にも対応しています。
connection.update({
in: "Table_Name",
set: {
Column1: value1,
Column2: value2
},
where: {
Column3: some_value,
Column4: some_another_value
}
}).then(function(rowsUpdated) {
alert(rowsUpdated + ' rows updated');
}).catch(function(err) {
console.log(err);
});
さらにテーブル構造の更新もできます。
var table1 = {
name: "table_name",
columns: [{
name: "column1",
dataType: 'datatype'
primaryKey: true
},
{
name: "column2",
dataType: 'datatype'
},
..... {
name: "columnN",
dataType: 'datatype'
}
],
version: 2 //Default version is 1.
}
JsStoreはIndexedDBを直接触った経験がある人であればお勧めしたいソフトウェアです。しかもWeb Workerにも対応しており、バックグラウンド処理でも活用できます。TypeScriptにも対応し、かなり実用的なライブラリと言えそうです。
JsStoreはTypeScript製のオープンソース・ソフトウェア(MIT)です。
JsStore - Think in SQL and do in JS ujjwalguptaofficial/JsStore: JsStore is an IndexedDB Wrapper. It makes IndexedDB super easy with its SQL like apis.