iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 20
1
Modern Web

30天走訪Progressive Web Apps(PWAs)系列 第 20

Day20-IndexedDB之流程統整

加入IndexedDB時提到它適合頻繁改變的內容,
那麼我們到firebase上,加入第二筆文章,看頁面的變化。

測試一: 加入第二筆資料

  1. firebase/Database,新增第2筆article
    https://ithelp.ithome.com.tw/upload/images/20180106/20103808ROJiBbRJYx.png

2.重整網頁
https://ithelp.ithome.com.tw/upload/images/20180106/20103808iQJzuI135c.png
會看到成功抓到兩筆文章,筆將新的一筆post-2也放進(put)IndexedDB裡面。

測試二: 文章內容變更

  1. firebase/Database,修改post-2content
    https://ithelp.ithome.com.tw/upload/images/20180106/201038083cdq6A9Xew.png

2.重整網站
https://ithelp.ithome.com.tw/upload/images/20180106/201038082pwUFUfIEI.png
網站內容也跟著更新!
這是因為put()會直接拿新資料覆蓋原本資料,所以文章內容能保持變更。

測試三: 刪除文章

  1. firebase/Database,新增第3筆article

  2. 重整網站,確認網頁存入IndexedDBarticle
    https://ithelp.ithome.com.tw/upload/images/20180106/20103808LpIBlXkVtw.png

  3. firebase/Database,刪除第3筆article

  4. 重整網站
    https://ithelp.ithome.com.tw/upload/images/20180106/20103808HlnlkK9mEP.png
    這時候,發現post-3還有在網頁上!
    那是因為put如果有內容時,會覆蓋現有的內容,
    如果現有的請求中(event.request),已沒有post-3的請求,那麼並不會觸發到它的變更。

要解決此問題,可以在fetch資源到資料庫前,將內容整個清除,再put,這樣就能保證資源正常,來實作一下。

實做清除

Step1: 新增清除所有資料的功能

function clearAllData(table){
    return dbPromise
            .then(function(db){
                var transaction = db.transaction(table, 'readwrite');
                var store = transaction.objectStore(table);
                store.clear();
                return transaction.complete;
            });
}

indexedDB.js中,加入一筆clearAllData,使用clear()功能,能直接將article中的所有內容清空,最後再回傳交易完成。

Step2: 修改Service Worker

            fetch(event.request)
                .then(function(response){
                    var copyRes = response.clone();
                    clearAllData('article')
                        .then(function(){
                            return copyRes.json();
                        })
                        .then(function(data){
                            console.log('copyRes.json()',data);
                            for(var key in data){
                                console.log('key',key);
                                writeData('article',data[key]);
                            }
                        });
                    return response;
                })

原本拿到文章的回應(response)後,就轉成json並寫入資料表,
現在要多一個步驟,先清除資料表內容後,再做原本的動作。
所以要再clearAllData完成後,再執行copyRes.json(),最後將資料存入資料表中。

測試

Step1: 更新Service Worker版號

var CACHE_STATIC = 'static-v8.4';
var CACHE_DYNAMIC = 'dynamic-v6.3';

Step2: 建立新的文章

https://ithelp.ithome.com.tw/upload/images/20180106/20103808iI6AkjScWM.png

https://ithelp.ithome.com.tw/upload/images/20180106/20103808n82fBzBRvs.png
確認IndexedDB順利存入3篇文章。

Step3: 刪除第3篇文章

https://ithelp.ithome.com.tw/upload/images/20180106/20103808yjHA7P93OA.png

Step4: 重整網頁

https://ithelp.ithome.com.tw/upload/images/20180106/20103808N0v519CDaE.png
現在頁面上的資料就跟firebase上的資料一致,代表清除資料表重新存入有效囉。

刪除/讀取指定文章

前面已經實作「寫入」、「清除」和「讀取」,現在稍微實作一下單筆「刪除」和「讀取」
來結束這個章節吧!

function deleteArticleData(table, id){
     return dbPromise
            .then(function(db){
                var transaction = db.transaction(table, 'readwrite');
                var store = transaction.objectStore(table);
                store.delete(id);
                return transaction.complete;
            });
}
function getArticleData(table, id){
    return dbPromise
            .then(function(){
                var transaction = db.transaction(table, 'readonly');
                var store = transaction.objectStore(table);
                return store.get(id);
            })
            .then(function(data){
                console.log('article:',data);
            });
}

刪除很簡單就將文章的key丟給delete()就刪除成功了。/images/emoticon/emoticon42.gif

總結

這兩三天,我們將專案加入IndexedDB的特色,讓離線的頁面可以有更多種工具來實現,
語法上有不會太難離解,唯一要注意的是javascript在執行上是非同步,在執行結果上,有時候會產生不一樣的結果,是可能發生的,所以,再使用Promise或一般function時,就要考慮執行的順序或觸發時間,才不會很難偵錯。

學習資源

idb: https://github.com/jakearchibald/idb
web Workers: https://developer.mozilla.org/zh-TW/docs/Web/API/Web_Workers_API/Using_web_workers
IndexedDB API: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
Google Developer: https://developers.google.com/web/ilt/pwa/working-with-indexeddb


上一篇
Day19-IndexedDB之抽成共用檔案
下一篇
Day21-Responsive Design
系列文
30天走訪Progressive Web Apps(PWAs)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言