Giter Club home page Giter Club logo

idb-store's Introduction

IndexedDB Promises ES6 Store Wrapper

ES6 class wrapper for creating and managing IndexedDB stores, built on top of jakearchibald idb lib.

Up and Running

npm install idb-store

Usage

const schemas = [
  {
    create: {
      name: 'item',
      options: {autoIncrement: true}
    },
    index: {
      name: 'myIndex',
      property: 'property',
      options: {unique: false}
    }
  }];

const DB = require('idb-store').DB;
const Store = require('idb-store').Store;

// Creates a new database.
DB.createDatabase('myDB', 1, schemas);

const db = new DB('myDB', 1);
const itemRepository = new Store('item', db);

// Creates a transactions and sets some data in the store.
itemRepository.set({ data: 42 })
  .then(itemRepository.getAll)
  .then(val => {
    console.log(val);
  });
});

// Opens a new connection and logs the database name.
db.open()
  .then(db.name)
  .then(name => {
    console.log('database name:', name);
  })
  .then(db.close)
});

DB

Static properties:

  • DB.hasSupport
  • DB.createDatabase
  • DB.deleteDatabase

db

Properties:

  • db.name
  • db.version
  • db.objectStoreNames

Methods:

  • db.close()
  • db.transaction()

Events:

  • onversionchange
  • onabort
  • onerror
  • onclose

Stores

Methods:

  • db[store].get()
  • db[store].set()
  • db[store].delete()
  • db[store].clear()
  • db[store].getAllKeys()
  • db[store].getAll()
  • db[store].count()

idb-store's People

Contributors

holmberd avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Forkers

yangxin1994

idb-store's Issues

Opening a new connection for every instance.

'use strict';

var idb = require('./idb.js');

/**
 * Class representing a IndexedDB objectStore.
 *
 * @constructor
 * @param {String} storeKey
 * @param {Promise} dbPromise
 * @returns {Store}
 */
class Store {
  constructor(storeKey, dbPromise) {
    this.dbPromise = dbPromise;
    this.storeKey = storeKey;
  }

  /**
   * Retrives a record or a range of records from the store.
   *
   * @param {Key|IDBKeyRange} key
   * @returns {Promise}
   */
  get(key) {
    return this.dbPromise.then(db => {
      return db.transaction(this.storeKey)
        .objectStore(this.storeKey).get(key);
    });
  }

  /**
   * Adds a new key value to the store.
   *
   * @param {*} val
   * @param {PrimaryKey} [key] - The primary key of the record
   * @returns {Promise}
   */
  set(val, key) {
    return this.dbPromise.then(db => {
      const tx = db.transaction(this.storeKey, 'readwrite');
      tx.objectStore(this.storeKey).put(val, key);
      return tx.complete;
    });
  }

  /**
   * Removes a key or a range of keys from the store.
   *
   * @param {Key|IDBKeyRange} key
   * @returns {Promise}
   */
  delete(key) {
    return this.dbPromise.then(db => {
      const tx = db.transaction(this.storeKey, 'readwrite');
      tx.objectStore(this.storeKey).delete(key);
      return tx.complete;
    });
  }

  /**
   * Clear all keys from the store.
   *
   * @returns {Promise}
   */
  clear() {
    return this.dbPromise.then(db => {
      const tx = db.transaction(this.storeKey, 'readwrite');
      tx.objectStore(this.storeKey).clear();
      return tx.complete;
    });
  }

  /**
   * Retrives all keys from the store or a range of keys.
   *
   * @param {IDBKeyRange} [query]
   * @param {Number} [count] -  Number of values to return
   * @returns {Promise}
   */
  getAllKeys(query, count) {
    return this.dbPromise.then(db => {
      const tx = db.transaction(this.storeKey);
      const keys = [];
      const store = tx.objectStore(this.storeKey);
      // store.getAllKeys()
      (store.iterateKeyCursor || store.iterateCursor).call(store, cursor => {
        if (!cursor) return;
        keys.push(cursor.key);
        cursor.continue();
      });

      return tx.complete.then(() => keys);
    });
  }

  /**
   * Retrives all records from the store.
   * If query is set then returns all records
   * that match the provided key or IDBKeyRange.
   *
   * @param {Key|IDBKeyRange} [query]
   * @param {Number} [count] - number of values to return
   */
  getAll(query, count) {
    return this.dbPromise.then(db => {
      const tx = db.transaction(this.storeKey);
      const store = tx.objectStore(this.storeKey);
      const keys = store.getAll(query, count);
      return tx.complete.then(() => keys);
    });
  }

  /**
   * Returns all records or the total number of records
   * that match the provided key or IDBKeyRange.
   *
   * @param {Key|IDBKeyrange} [query]
   * @returns {Promise}
   */
  count(query) {
    return this.dbPromise.then(db => {
      return db.transaction(this.storeKey)
        .objectStore(this.storeKey).count(query);
    });
  }

}

/**
 * An object containing idb object store schema.
 *
 * @typedef {Object} StoreSchema
 * @property {Object} create
 * @property {String} create.name
 * @property {Object} create.options
 * @property {Object} index
 * @property {String} index.name
 * @property {String} index.property
 * @property {Object} index.options
 */

/**
 * Class representing a open IDBDatabase object.
 *
 * @constructor
 * @param {String} dbName
 * @param {Number} version
 * @returns {DB}
 */
class DB {
  constructor(dbName, version) {
    this.dbPromise = null;
    this.open(dbName, version);
  }

  /**
   * Opens a connection to the database and adds the stores to the DB instance.
   *
   * @param {String} dbName
   * @param {Number} version
   * @returns {Promise}
   */
  open(dbName, version) {
    const dbPromise = idb.open(dbName, version).then(db => {
      const names = db.objectStoreNames;
      for (var i = 0; i < names.length; i++) {
        this[names[i]] = new Store(names[i], this.dbPromise);
      }
    });
    this.dbPromise = dbPromise;
    return dbPromise;
  }

  /**
   * Creates a new database.
   * 
   * @param {String} dbName
   * @param {Number} version
   * @param {StoreSchema[]}
   * @returns {Promise}
   */
  static createDatabase(dbName, version, storesSchema) {
    const dbPromise = idb.open(dbName, version, upgradeDB => {
      let store = null;
      storesSchema.forEach(storeSchema => {
        if (!upgradeDB.objectStoreNames.contains(storeSchema.create.name)) {
          store = upgradeDB.createObjectStore(storeSchema.create.name, storeSchema.create.options);
          if (storeSchema.hasOwnProperty('index')) {
            store.createIndex(storeSchema.index.name, storeSchema.index.property, storeSchema.index.options);
          }
        }
      });
    });
    return dbPromise.then(db => {
      return db.close();
    });
  }

  /**
   * Deletes a database.
   *
   * @param {String} dbName
   * @returns {Promise}
   */
  static deleteDatabase(dbName) {
    return idb.delete(dbName);
  }

  /**
   * Fired when a database structure change.
   *
   * @listens IDBOpenDBRequest.onupgradeneeded | IDBFactory.deleteDatabase
   * @returns {Promise}
   */
  onversionchange() {
    return new Promise((resolve, reject) => {
      return this.dbPromise.then(db => {
        db._db.onversionchange = function(err) {
          resolve(err);
        };
      });
    });
  }

  /**
   * Fired after all transactions have been aborted and the connection has been closed.
   *
   * @listens close
   * @returns {Promise}
   */
  onclose() {
    return new Promise((resolve, reject) => {
      return this.dbPromise.then(db => {
        db._db.onclose = function(err) {
          resolve(err);
        };
      });
    });
  }

  /**
   * Fired when a request returns an error and bubbles up to the connection object.
   *
   * @listens error
   * @returns {Promise}
   */
  onerror() {
    return new Promise((resolve, reject) => {
      return this.dbPromise.then(db => {
        db._db.onerror = function(err) {
          resolve(err);
        };
      });
    });
  }

  /**
   * Fired when a transaction is aborted and bubbles up to the connection object.
   *
   * @listens abort
   * @returns {Promise}
   */
  onabort() {
    return new Promise((resolve, reject) => {
      return this.dbPromise.then(db => {
        db._db.onabort = function(err) {
          resolve(err);
        };
      });
    });
  }

  /**
   * Returns the db name.
   *
   * @returns {Promise}
   */
  get name() {
    return this.dbPromise.then(db => {
      return db.name;
    });
  }

  /**
   * Returns the db version.
   *
   * @returns {Promise}
   */
  get version() {
    return this.dbPromise.then(db => {
      return db.version;
    });
  }

  /**
   * Returns all store names.
   *
   * @returns {Promise}
   */
  get objectStoreNames() {
    return this.dbPromise.then(db => {
      let names = db.objectStoreNames;
      let buffer = [];
      for (var i = 0; i < names.length; i++) {
        buffer.push(names[i]);
      }
      return buffer;
    });
  }

  /**
   * Closes connection to the db.
   *
   * @returns {Promise}
   */
  close() {
    return this.dbPromise.then(db => {
      return db.close();
    });
  }

  /**
   * Returns a transaction object(IDBTransaction).
   *
   * @param {String[]|IDBDatabase.objectStoreNames} [storeNames]
   * @param {String} [mode]
   */
  transaction(storeNames, mode) {
    return this.dbPromise.then(db => {
      return db.transaction(storeNames, mode);
    });
  }

  /**
   * Checks if indexedDB is supported.
   *
   * @static
   * @readonly
   * @returns {Boolean}
   */
  static get hasSupport() {
    if (!('indexedDB' in window)) {
      console.warn('This environment doesn\'t support IndexedDB');
      return false;
    }
    return true;
  }
}

module.exports = DB;
const DB = require('db');
DB.createDatabase('test', 1, {});
var db = new DB('test', 1);
db.win.getAll().then(res => console.log(res));
db.close();

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.