import { Injectable } from '@angular/core'; import { Platform } from 'ionic-angular'; import PouchDB from 'pouchdb'; import * as Relational from 'relational-pouch'; import * as Sqlite from 'pouchdb-adapter-cordova-sqlite'; import each from 'async/each'; PouchDB.plugin(Relational).plugin(Sqlite); @Injectable() export class DataProvider { data: any; schema: Array = [ { singular: 'partner', plural: 'partners' }, { singular: 'user', plural: 'users' }, { singular: 'currency', plural: 'currencies' }, { singular: 'company', plural: 'companies' }, { singular: 'product_template', plural: 'product_templates' }, { singular: 'warehouse', plural: 'warehouses', }, { singular: 'stock', plural: 'stocks' }, { singular: 'lead', plural: 'leads' }, { singular: 'product_attribute', plural: 'product_attributes' }, { singular: 'product_attribute_line', plural: 'product_attribute_lines' }, { singular: 'product_attribute_value', plural: 'product_attribute_values' }, { singular: 'product', plural: 'products' } ]; constructor( public platform: Platform ) { this.initialize(); } /** * */ private initialize(): void { this.data = new PouchDB('odoo', { auto_compaction: true, adapter: this.platform.is('core') ? 'idb' : 'websql' }); this.data.setSchema(this.schema); } /** * */ private getPlural(singular: string) { for (let i = 0; i < this.schema.length; i++) { if (this.schema[i].singular === singular) { return this.schema[i].plural; } } return null; } /** * Save object or array of objects to database * @argument type: string * @argument data: object or array of objects */ save(type: string, data: any): Promise { return new Promise((resolve, reject) => { if (data instanceof Array) { each(data, (i, c) => { this.data.rel.save(type, i).then(() => { c(); }).catch(e => { c(e); }); }, e => { if (e) { reject(e); } else { resolve(); } }); } else { this.data.rel.save(type, data).then(doc => { resolve(doc[this.getPlural(type)][0]); }).catch(e => { reject(e); }); } }); } /** * */ delete(type: string, data: any): any { return new Promise((resolve, reject) => { this.platform.ready().then(r => { resolve(data.remote_id ? this.save(type, data) : this.data.rel.del(type, data)); }); }); } /** * */ deleteAll(type: string): Promise { return new Promise((resolve, reject) => { this.getAll(type).then(data => { each(data[type], (i, c) => { this.data.rel.del(type, i).then(r => { c(); }).catch(e => { c(e); }); }, e => { if (e) { reject(e); } else { resolve(); } }); }).catch(e => { reject(e); }); }); } /** * */ getAll(type: string): Promise { return new Promise((resolve, reject) => { this.data.rel.find(type).then(result => { resolve(result[this.getPlural(type)]); }).catch(e => { reject(e); }); }); } /** * */ dropDatabase(): any { return new Promise((resolve, reject) => { resolve(this.data.destroy()); }); } /** * */ parseDocID(id: string): any { return this.data.rel.parseDocID(id); } }