Skip to content

Instantly share code, notes, and snippets.

@santaklouse
Last active February 26, 2020 14:01
Show Gist options
  • Select an option

  • Save santaklouse/0c9b457a66ec5ffede44419dd3f94cd7 to your computer and use it in GitHub Desktop.

Select an option

Save santaklouse/0c9b457a66ec5ffede44419dd3f94cd7 to your computer and use it in GitHub Desktop.
draft for angularJs cache storage based on indexedDB
(function(angular){
'use strict';
angular.module('test.services.indexed_db', [])
.factory('CRC32', function () {
let makeCRCTable = () => {
let c,
crcTable = [],
n = 0;
for ( ; n < 256; n++) {
c = n;
for (let k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
crcTable[n] = c;
}
return crcTable;
};
this.crcTable = makeCRCTable();
return str => {
let crc = 0 ^ (-1),
i = 0, l = str.length;
for (; i < l; i++) {
crc = (crc >>> 8) ^ this.crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
}
return (crc ^ (-1)) >>> 0;
};
})
.factory('persistanceService', ['$window', '$document', '$q', 'CRC32', function ($window, $document, $q, CRC32) {
this.setUp = false;
this.openRequest = null;
// IndexedDB
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB,
IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.OIDBTransaction || window.msIDBTransaction,
dbVersion = 1.0;
let calculateHash = item => {
return CRC32(item);
};
let init = () => {
var deferred = $q.defer();
if(this.setUp && this.openRequest) {
deferred.resolve(this.openRequest);
return deferred.promise;
}
this.openRequest = indexedDB.open("indexeddb_storage", dbVersion);
this.openRequest.onerror = e => {
console.log("Error opening db");
console.dir(e);
deferred.reject(e.toString());
};
this.openRequest.onupgradeneeded = function(e) {
var thisDb = e.target.result;
var objectStore;
//Create Note OS
if(!thisDb.objectStoreNames.contains("cached_images")) {
objectStore = thisDb.createObjectStore("cached_images", { keyPath: "id", autoIncrement:true });
objectStore.createIndex("content", "content", { unique: false });
objectStore.createIndex("hash", "hash", { unique: true });
// objectStore.createIndex("tags","tags", {unique:false, multiEntry:true});
}
};
this.openRequest.onsuccess = function(e) {
let db = e.target.result;
db.onerror = function(event) {
// Generic error handler for all errors targeted at this database's
// requests!
deferred.reject("Database error: " + event.target.errorCode);
};
this.setUp = true;
deferred.resolve(this.openRequest);
};
return deferred.promise;
};
let getByHash = hash => {
let deferred = $q.defer();
init().then(db => {
const transaction = db.transaction(['cached_images'], IDBTransaction.READ_ONLY);
const invStore = transaction.objectStore('cached_images');
const vendorIndex = invStore.index('hash');
const keyRng = IDBKeyRange.only(hash);
const cursorRequest = vendorIndex.openCursor(keyRng);
cursorRequest.onsuccess = e => {
const cursor = e.target.result;
if (cursor) {
deferred.resolve(cursor.value);
cursor.continue();
}
}
});
return deferred.promise;
};
let isExists = hash => {
let deferred = $q.defer();
init().then(db => {
const transaction = db.transaction(['cached_images'], IDBTransaction.READ_ONLY);
const invStore = transaction.objectStore('cached_images');
const vendorIndex = invStore.index('hash');
const keyRng = IDBKeyRange.only(hash);
const cursorRequest = vendorIndex.openCursor(keyRng);
cursorRequest.count().onsuccess = function(event) {
const count = event.target.result;
if (count) {
return deferred.resolve(event.target.result);
}
deferred.reject();
};
});
return deferred.promise;
};
let saveImage = (content, hash = false) => {
hash = hash || calculateHash(content);
init().then(db => {
var tx = db.transaction('cached_images', IDBTransaction.READ_WRITE);
var store = tx.objectStore('cached_images');
store.add({
hash: hash,
content: content,
created: new Date().getTime()
});
return tx.complete;
}).then(function() {
console.log('added item to the store os!');
});
return hash;
};
return {
init: init,
saveImage: saveImage,
isExists: isExists,
getByHash: getByHash
};
}]);
})(angular);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment