Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // image_idb.js
- import { openDB/*, deleteDB, wrap, unwrap*/ } from 'idb@7.min';
- export const dbName = 'YourIDBName';
- export const dbVersion = 1;
- export const storeName = {images: 'images'};
- export const localImageCheck = (
- dbName,
- storeName,
- id,
- el,
- onNoIDB = (el, url) => {},
- onUndefined = (request) => {},
- onOutdated = (request) => {},
- onDefined = (request) => {}
- ) => {
- let url = $(el).data('image-src');
- //console.log(url);
- // Check for image blob in a local indexedDB
- if(url !== undefined) {
- if(!('indexedDB' in window)) {
- // If browser doesn't support indexedDB. Needs additional logic added to alert end user of
- // data consuption and alternative methods.
- onNoIDB(el, url);
- }
- else {
- //console.log({dbName: dbName, dbVersion: dbVersion});
- openDB(dbName, dbVersion, {
- upgrade(db) {
- db.createObjectStore(storeName, {keyPath: 'id'});
- },
- }).then(
- (db) => {
- //console.log(db);
- let transaction = db.transaction(storeName);
- //console.log(transaction);
- transaction.store.get(id).then(
- (result) => {
- //console.log(result);
- if(result == undefined) onUndefined(el, result);
- else if(result.url != url) onOutdated(el, result);
- else onDefined(el, result.blob);
- },
- (error) => {
- console.error('IDB.store.get():', error);
- }
- );
- },
- (error) => {
- console.error('IDB.openDB():', error);
- onNoIDB(el, url);
- }
- )
- }
- }
- else onUndefined();
- }
- export const localImageStore = (dbName, storeName, id, el, method, localImagePut = (el, blob, pulled) => {}) => {
- let url = $(el).data('image-src');
- //console.log(url);
- if(url !== undefined) {
- let xhr = new XMLHttpRequest();
- xhr.responseType = 'blob';
- xhr.open('GET', url, true);
- xhr.addEventListener("load", () => {
- if (xhr.readyState == 4 && xhr.status === 200) {
- //console.log(xhr);
- // Put/get image blobs in a local indexedDB
- openDB(dbName, 1, {
- upgrade(db) {
- db.createObjectStore(storeName, {keyPath: 'id'});
- },
- }).then(
- (db) => {
- let transaction = db.transaction(storeName, 'readwrite');
- let image = {
- id: id,
- url: url,
- blob: xhr.response
- }
- if(method == 'ADD') {
- //console.log(`ADD: ${image}`);
- let objStore = transaction.store.add(image).then(
- (key) => {
- localImagePut(el, xhr.response, true);
- },
- (error) => {
- console.error('IDB.store.add():', error);
- }
- );
- }
- else if(method == 'PUT') {
- //console.log(`PUT: ${image}`);
- let objStore = transaction.store.put(image).then(
- (key) => {
- localImagePut(el, xhr.response, true);
- },
- (error) => {
- console.error('IDB.store.put():', error);
- }
- );
- }
- },
- (error) => {
- console.error('IDB.openDB():', error);
- }
- );
- }
- else {
- console.log("Error", xmlhttp.statusText);
- }
- }, false);
- xhr.send();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement