April 21, 2020 [ Web ]
Indexeddbを使うならラッパーが要るやろ、とオモて、溺死やったらコレ便利やんってちゃうか、とオモて、知らんけ縺?
■構造 DB > Table > kvs > record
(db=)schedule_db > schedule(=table) > kvs(Key=自動採逡?:Value=json=record)
kvs縺?id++が先頭に来ずでこう→ 1:"{"name":"aaa",reg_date":"20201027_11:57:24","id":1}"
var db = new Dexie("schedule_db");
db.version(1).stores({
schedule: '++id,name,reg_date'
});
■操作
var db = new Dexie("schedule_db"); schedule_dbというDBがセットされ
schedule: '++id,name,key,reg_date' テーブ繝?scheduleにカウントアップKey:JSON{id,name,key,reg_date}が入る
もしschedule: 'name,key,reg_date'ならnameが自動で臀??番最初のカラムだからキーになる
キーの値が同じだ縺?Addができない
stores()で臀??番最初に来るのが「主キー」
put()は追加しあれば更新、add()は追加のみで同キーがあればエラ繝?
put()縺?updateとし縺?DB上上書きされるように鐔??えるがループすると全データが出て縺?る、隰?
first()やlimit()やlast()で欲しいレコードを藹??得
toArray()で縺?objが返るがobjは配列で藹??謨?0をつけてアクセ繧? obj[0]
get('aaa')縺?key=aaaの値を持つ最初の鐔??、get({key: "sss", value: "ccc"})で条件付藹??
delete()の鐔??り蛟?Promiseに削除件数が入っている
■削除のレベルは鐔??、表、DB
行削髯? db.schedule.where({id: id}).delete().then (function(records){
表削髯? trancateで db.schedule.clear(); コンソールには藹??映されていないがレコード削除觸??
db.table(storeName) で操作あるい縺?tables ->だめだった
表を複数持てる
db.version(1).stores({
genres: '++id,name',
albums: '++id,name,year,*tracks',
bands: '++id,name,*albumIds,genreId'
});
db.delete() DBを消せる(その藹??新たに再作成できる)
■insert
db.schedule.add({name: "aaa", key: "bbb", reg_date: getCurrentTime()}).then (function(id){
return db.schedule.get(id);
}).then(function (schedule) {
alert ("Date was set at " + schedule.reg_date);
■select
db.reserve.each(function(records){
if(records == null || records == ''){
alert ("No data found");
}else{
records.json;
toArrayは鐔??雑になる、eachの方がよいかも、toArray縺?eachの入れ替えて縺?select発鐔??が基本できるみたい
db.reserve.where({flg_del: 2}).toArray(function(records){
records.forEach(function(record){//obj.forEach直で鐔??ける
Object.keys(record).forEach(function(key) {//直で鐔??けずObject.keys().forEach()縺?
let val = this[key];
if(key == 'json'){
let v = JSON.parse(val);//直で鐔??けずパースが必要
Object.keys(v).forEach(function(k) {
let v = this[k];
console.log(k, v);
}, v);
}
}, record);
});
複雑なもの縺?Or句で出せる
db.reserve.where('reg_date').below(getCurrentTime()).or('flg_del').equals(2).limit(3).each(function(records){
console.log('List: ' + JSON.stringify(records));
And句縺?functionを藹??るが簡単な感じがする
db.reserve.where('datetime').below(display_expire_date).and(item => item.flg_del == 2).desc('datetime').limit(display_ex).each(function(records){
複数条件縺?whereにオブジェクトとして鐔??載するがbelow等のフィルターにつながらずエラー、シンプルならokだが
db.reserve.where({datetime, flg_del: 2}).below(display_expire_date).limit(display_ex).each(function(records){
複数条件にフィルターをつけるに縺?whereに配列で鐔??載するが一つ縺?below、一つ縺?equalsでフィルタが複数でうま縺?いかない、シンプルならokだが
db.reserve.where(["datetime", "flg_del"]).below([display_expire_date, 2]).limit(display_ex).each(function(records){
先頭鐔??
db.schedule.where('name').equals('aaa').first().then (function(records){
x↓ダ繝???
db.schedule.where('name').equals('aaa').toArray(function(records){
alert(records.reg_date);
x↓ダ繝???
db.schedule.get({name: "aaa", key: "bbb"}).then (function(records){
alert (JSON.stringify(records));
for (let i in records) {
alert(i + ' item has ' + records[i].reg_date);
}
■Insert and select(キー縺?idを使う)
db.schedule.add({name: "ver1.0", key: document.getElementById("inputKey").value, value: document.getElementById("inputValue").value, reg_date: getCurrentTime()}).then(function(){
db.schedule.get('2').then(function(records){
alert(JSON.stringify(records));
}).catch(function(error) {
alert ("Ooops: " + error);
});
}).catch(function(error) {
alert ("Ooops2: " + error);
■Update
putは藹??在があれば更新、なければ挿蜈?
db.schedule.put({key: "bbb", reg_date: set_date}).then (function(){
return db.schedule.get('bbb');
}).then(function (schedule) {
alert ("Date was set at " + schedule.reg_date);
keyが出せる場合縺?update()
db.friends.update(2, {name: "Number 2"}).then(function (updated) {
トランザクションや細かな藹??更縺?modify()
db.friends.where("shoeSize").aboveOrEqual(47).modify({isBigfoot: 1});
modify推奨・??→ https://dexie.org/docs/Collection/Collection.modify()
■Delete
db.schedule.where({name: "aaa"}).delete().then (function(){
return db.schedule.toArray();
}).then(function (records) {
if(records == null || records == ''){
alert ("No data found");
}else{
alert (JSON.stringify(records));
}
■アクセ繧?
indexeddbは該当DBにどこからアクセスできるか>同一ドメイン、ディレクトリでじゃない
保存場所
C:\Users\<ユー繧?>\AppData\Local\Google\Chrome\User Data\Default\IndexedDB
C:\Users\<ユー繧?>\AppData\Roaming\Mozilla\Firefox\Profiles\XXXXX.default\storage\default
■課饅??
SWで藹??驛?JSを扱うに縺?SW内に importScripts('dexie.js'); で埋め込む
SyntaxError: Unexpected token o in JSON at position 1 はオブジェクトが返っている
JSONはオブジェクトで扱うのが讌? JSON.stringify(records)縺?JSON.parse(records)で藹??觸??
console.log('json: ' + JSON.stringify(json));
for(i = 0; i < json.length; i++){
if(json[i] != null) {
console.log('id: ' + json[i].id);
下のようなロジックはあるテーブル縺?SELECTループ中に臀??のテーブルにアクセスする入れ子なのでエラー「NotFoundError: Failed to execute 'objectStore' on 'IDBTransaction': The specified object store was not found.」→配列に入れ縺?IndeDBの蝠?い合繧?せを一旦藹??了し、配列のループ縺?Indedbを操作
self.addEventListener('sync', function(event){
db.que.each(function(records){
if(event.tag.startsWith('post-data:' + records.tag)){
event.waitUntil(postDataSW(db));
}
});
function postDataSW(){
db.reserve.where({flg_server: 2}).toArray(function(records){
DevTools failed to load SourceMap: Could not load content~のエラーが出た
効果あるか不譏?だがdexieの最終行のコレを削除した、文字コードがUTF8に藹??えたりも //# sourceMappingURL=include.prepload.js.map
■関騾?JS、Javascript
JS縺?Aタグリンクを挿入するに縺?insertAdjacentHTMLがよい
生成したタグを追加する前に觸??除するに縺?document.getElementById('xx').textContent = null;
■テスト
https://www.bangboo.com/indexeddb/indexeddb_dexie_form.html
https://www.bangboo.com/indexeddb/test/indexeddb_dexie_form.html (ディレクトリ違い)
Posted by funa : 12:00 AM