import { Injectable } from "@angular/core" ; import { Platform } from "ionic-angular" ; const DB_NAME = '__mojoapp' ; const win = window ; @ Injectable ( ) export class Sql { private _dbPromise : Promise < any > ; constructor ( public platform ) { this . _dbPromise = new Promise ( ( resolve , reject ) => { try { let _db ; this . platform . ready ( ) . then ( ( ) => { if ( this . platform . is ( 'cordova' ) && win . sqlitePlugin ) { _db = win . sqlitePlugin . openDatabase ( { name : DB_NAME , location : 'default' } ) ; } else { console . warn ( 'Storage: SQLite plugin not installed, falling back to WebSQL. Make sure to install cordova-sqlite-storage in production!' ) ; _db = win . openDatabase ( DB_NAME , '1.0' , 'database' , 5 * 1024 * 1024 ) ; } resolve ( _db ) ; } ) ; } catch ( err ) { reject ( { err : err } ) ; } } ) ; this . _tryInit ( ) ; } _tryInit ( ) { this . query ( 'CREATE TABLE IF NOT EXISTS kv (key text primary key, value text)' ) . catch ( err => { console . error ( 'Storage: Unable to create initial storage tables' , err . tx , err . err ) ; } ) ; } param { string } query param { array } params return { Promise } query ( query , params = [ ] ) { return new Promise ( ( resolve , reject ) => { try { this . _dbPromise . then ( db => { db . transaction ( ( tx ) => { tx . executeSql ( query , params , ( tx , res ) => resolve ( { tx : tx , res : res } ) , ( tx , err ) => reject ( { tx : tx , err : err } ) ) ; } , ( err ) => reject ( { err : err } ) ) ; } ) ; } catch ( err ) { reject ( { err : err } ) ; } } ) ; } param { string } key return { Promise } get ( key ) { return this . query ( 'select key, value from kv where key = ? limit 1' , [ key ] ) . then ( data => { if ( data . res . rows . length > 0 ) { return data . res . rows . item ( 0 ) . value ; } } ) ; } param { string } key param { string } value return { Promise } set ( key , value ) { return this . query ( 'insert or replace into kv(key, value) values (?, ?)' , [ key , value ] ) ; } getJson ( key ) { return this . get ( key ) . then ( value => { try { return JSON . parse ( value ) ; } catch ( e ) { throw e ; } } ) ; } setJson ( key , value ) { try { return this . set ( key , JSON . stringify ( value ) ) ; } catch ( e ) { return Promise . reject ( e ) ; } } param { string } key return { Promise } remove ( key ) { return this . query ( 'delete from kv where key = ?' , [ key ] ) ; } return { Promise } clear ( ) { return this . query ( 'delete from kv' ) ; } }