gilf / angular2-indexeddb

angular2-indexeddb is a library that wraps indexeddb database in an Angular service.
MIT License
88 stars 44 forks source link
angular indexeddb javascript

angular2-indexeddb

angular2-indexeddb is a service that wraps IndexedDB database in an Angular service. It exposes very simple promises API to enable the usage of IndexedDB without most of it plumbing.

Copyright (C) 2017, Gil Fink gil@sparxys.com

Installation

You can choose your preferred method of installation:

Usage

Include angular2-indexeddb.js in your application.

<script src="https://github.com/gilf/angular2-indexeddb/raw/master/components/angular2-indexeddb/angular2-indexeddb.js"></script>

Import the the AngularIndexedDB class as a dependency:

import {AngularIndexedDB} from 'angular2-indexeddb';

AngularIndexedDB service

First instantiate the service as follows:

let db = new AngularIndexedDB('myDb', 1);

The first argument is the name of your database and the second is the database version. If you forget the version you the service will default to version 1.

Use the APIs that the AngularIndexedDB service exposes to use indexeddb. In the API the following functions:

Usage example:

db.openDatabase(1, (evt) => {
    let objectStore = evt.currentTarget.result.createObjectStore(
        'people', { keyPath: "id", autoIncrement: true });

    objectStore.createIndex("name", "name", { unique: false });
    objectStore.createIndex("email", "email", { unique: true });
});

Usage example:

db.getByKey('people', 1).then((person) => {
    console.log(person);
}, (error) => {
    console.log(error);
});

Usage example:

db.getAll('people').then((people) => {
    console.log(people);
}, (error) => {
    console.log(error);
});

Usage example:

db.getByIndex('people', 'name', 'Dave').then((person) => {
    console.log(person);
}, (error) => {
    console.log(error);
});

Usage example (add without a key):

db.add('people', { name: 'name', email: 'email' }).then(() => {
    // Do something after the value was added
}, (error) => {
    console.log(error);
});

In the previous example I'm using undefined as the key because the key is configured in the objectStore as auto-generated.

Usage example (update without a key):

db.update('people', { id: 3, name: 'name', email: 'email' }).then(() => {
    // Do something after update
}, (error) => {
    console.log(error);
});

Usage example:

db.delete('people', 3).then(() => {
    // Do something after delete
}, (error) => {
    console.log(error);
});

Usage example:

db.openCursor('people', (evt) => {
    var cursor = (<any>evt.target).result;
    if(cursor) {
        console.log(cursor.value);
        cursor.continue();
    } else {
        console.log('Entries all displayed.');
    }
}, IDBKeyRange.bound("A", "F"));

Usage example:

db.clear('people').then(() => {
    // Do something after clear
}, (error) => {
    console.log(error);
});

License

Released under the terms of the MIT License.