Skip to content

indexeddb-promise 6.1.1

Install from the command line:
Learn more about npm packages
$ npm install @n1md7/indexeddb-promise@6.1.1
Install via package.json:
"@n1md7/indexeddb-promise": "6.1.1"

About this version

npm databaseVersion Node.js Package Node.js CI - tests GitHub codecov

Indexed DB wrapper with promises

Demo

Installation

npm install @n1md7/indexeddb-promise --save
# or
yarn add @n1md7/indexeddb-promise

Available methods

  • select
  • insert
  • selectAll
  • openCursor
  • selectByIndex
  • selectByPk
  • updateByPk
  • deleteByPk

.selectAll(): Promise

Gets all the data from db and returns promise with response data

.selectByIndex(indexName: string, valueToMatch: string): Promise

Gets data from the db and returns promise with response data

.selectByPk(pKey: string): Promise

Has one parameter pkey as primaryKey and returns promise with data

.select({...}): Promise

Has one parameter props which can be

const props = {
  limit: 10,
  where: (dataArray) => {
    return dataArray;
  },
  orderByDESC: true,
  sortBy: 'comments', // ['comments', 'date']
};

@where property can filter out data like

const props = {
  where: (data) => data.filter((item) => item.username === 'admin'),
};

or it can be an object, which gets data with AND(&&) comparison

const props = {
  where: {
    username: 'admin',
    password: 'admin123',
  },
};

.updateByPk(pKey: string | number, {...}): Promise

Has two parameters pkey and keyValue pair of updated data

updateByPk(123, { username: 'admin' });

.deleteByPk(pKey): Promise

Has one parameter pKey which record to delete based on primary key

note primary key is type sensitive. If it is saved as integer then should pass as integer and vice versa

Usage example

<html>
  <head>
    <title>IndexedDB app</title>
    <script src="./dist/indexed-db.min.js"></script>
  </head>
  <body>
    <script>
      // Your script here
    </script>
  </body>
</html>

Once you add indexed-db.min.js in your document then you will be able to access IndexedDB variable globally which contains Model. They can be extracted as following

const { Database } = IndexedDB;

// or
const Database = IndexedDB.Database;

Create connector and pass the config

const db = new IndexedDB.Database({
  databaseVersion: 1,
  databaseName: 'myNewDatabase',
  tables: [
    {
      name: 'myNewTable',
      primaryKey: {
        name: 'id',
        autoIncrement: false,
        unique: true,
      },
      initData: [],
      indexes: {
        username: { unique: false, autoIncrement: false },
        password: { unique: false, autoIncrement: false },
      },
      timestamps: true,
    },
  ],
});

Full example

<html>
  <head>
    <title>IndexedDB app</title>
    <script src="./dist/indexed-db.min.js"></script>
  </head>
  <body>
    <script>
      const db = new IndexedDB.Database({
        databaseVersion: 1,
        databaseName: 'myNewDatabase',
        tables: [
          {
            name: 'myNewTable',
            primaryKey: {
              name: 'id',
              autoIncrement: false,
              unique: true,
            },
            initData: [],
            indexes: {
              username: { unique: false, autoIncrement: false },
              password: { unique: false, autoIncrement: false },
            },
          },
        ],
      });

      // add a new record
      const model = db.useModel('myNewTable');
      model
        .insert({
          id: Math.random() * 10,
          username: 'admin',
          password: 'nimda',
          createdAt: new Date(),
          updatedAt: new Date(),
        })
        .then(function () {
          console.info('Yay, you have saved the data.');
        })
        .catch(function (error) {
          console.error(error);
        });

      // Get all results from the database
      model.selectAll().then(function (results) {
        console.log(...results);
      });
    </script>
  </body>
</html>
const IndexedDB = require('@n1md7/indexeddb-promise');
const { Database } = IndexedDB;
// or
import { Database } from '@n1md7/indexeddb-promise';

TypeScript example

import { Database } from '@n1md7/indexeddb-promise';

interface Users {
  id?: number;
  username: string;
  password: string;
}

enum Priority {
  LOW = 'LOW',
  MEDIUM = 'MEDIUM',
  HIGH = 'HIGH',
}

interface ToDos {
  id?: number;
  userId: number;
  title: string;
  description: string;
  done: boolean;
  priority: Priority;
}

const database = new Database({
  version: 1,
  name: 'Todo-list',
  tables: [
    {
      name: 'users',
      primaryKey: {
        name: 'id',
        autoIncrement: true,
        unique: true,
      },
      indexes: {
        username: {
          unique: false,
        },
      },
      timestamps: true,
    },
    {
      name: 'todos',
      primaryKey: {
        name: 'id',
        autoIncrement: true,
        unique: true,
      },
      indexes: {
        userId: {
          unique: true,
        },
      },
      timestamps: true,
    },
  ],
});

(async () => {
  const users = database.useModel<Users>('users');
  const user = await users.insert({
    username: 'admin',
    password: 'admin',
  });
  const todos = database.useModel<ToDos>('todos');
  await todos.insert({
    userId: user.id,
    title: 'Todo 1',
    description: 'Description 1',
    done: false,
    priority: Priority.LOW,
  });
})();
import { Table, PrimaryKey, Indexed, Database } from '@n1md7/indexeddb-promise';

@Table({ name: '__Name__', timestamps: true })
class SomeTable {
  @PrimaryKey({ autoIncrement: true, unique: true })
  id: number;

  @Indexed({ unique: true, multiEntry: false })
  username: string;

  @Indexed({ unique: false })
  age: number;

  otherData: string;
}

const anotherDb = new Database({
  version: 1,
  name: 'Other-DB',
  tables: [SomeTable],
});

const model = anotherDb.useModel(SomeTable);

(async () => {
  await model
    .insert({
      username: 'John',
      age: 20,
      otherData: 'Some data',
    })
    .catch((error) => console.error(error));

  model.selectAll().then((results) => {
    if (results) {
      results.forEach((result) => {
        // result is inferred to be SomeTable
        console.log(result.username);
      });
    }
  });
})();

Details


Assets

  • indexeddb-promise-6.1.1-npm.tgz

Download activity

  • Total downloads 0
  • Last 30 days 0
  • Last week 0
  • Today 0