Skip to content

Instantly share code, notes, and snippets.

@justinramel
Created December 24, 2015 11:48
Show Gist options
  • Save justinramel/d24020065d73eb08fb3c to your computer and use it in GitHub Desktop.
Save justinramel/d24020065d73eb08fb3c to your computer and use it in GitHub Desktop.
Ionic 2 blog series - Rates service
import {Storage, SqlStorage} from 'ionic/ionic';
export class CustomStorage {
constructor() {
this.db = new Storage(SqlStorage);
}
getDB() {
return this.db._strategy._db;
}
query(sql, params = []) {
return new Promise((resolve, reject) => {
try {
this.getDB().transaction(tx => {
tx.executeSql(sql, params, (tx, success) => {
resolve(success);
}, (tx, error) => {
reject(error);
});
});
} catch (error) {
reject(error);
}
});
}
}
import {CustomStorage} from '../storage/custom-storage';
import * as _ from 'lodash';
export class RatesService {
constructor() {
this.storage = new CustomStorage();
this.createRatesTableIfItDoesNotExist();
}
all() {
return this.storage.query('select * from rates').then(result => {
return _.map(result.rows, row => {
return {
id: row.id,
createdDate: new Date(row.createdDate),
direction: row.direction,
description: row.description,
amount: row.amount,
days: row.days,
dailyRate: row.dailyRate
};
});
}).catch(error => {
console.log(error);
});
}
create(direction) {
return {
createdDate: new Date(),
direction: direction,
description: '',
amount: 0,
days: 30,
dailyRate() {
return this.amount / this.days;
}
};
}
save(rate) {
return this.storage.query(`insert into rates(
createdDate,
direction,
description,
amount,
days,
dailyRate
) values (?, ?, ?, ?, ?, ?)`,
[
rate.createdDate.getTime(),
rate.direction,
rate.description,
rate.amount,
rate.days,
rate.dailyRate()
]).then(result => {
rate.id = result.insertId;
return rate;
}).catch(error => {
console.error('Error saving rate', error);
});
}
createRatesTableIfItDoesNotExist() {
const createSql = `create table if not exists rates(
id integer primary key autoincrement,
createdDate long,
direction text,
description text,
amount real,
days integer,
dailyRate real
)`;
this.storage.query(createSql).catch(error => {
console.error('Error creating rates table', error);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment