/**
* A storage class to store information on a device
*
* It follows a structure similar to relational databases
*
* Basic usage example:
* ```js
* let storage = new Storage('tableName');
* ```
*/
export default class Storage {
/**
* The name of the table where all the
* records is be saved
*/
tableName: string;
/**
* Storage constructor
*
* @param table Table name
*/
constructor(tableName: string) {
this.tableName = tableName;
}
/**
* Returns the table name
*/
getTableName(): string {
return this.tableName;
}
/**
*
* @param value Any object or Array of object to save
*
* Example:
* ```js
* storage.insert({ id: 1, name: 'John', lastname: 'Doe'});
* ```
*/
insert(value: any): void {
let table = window.localStorage.getItem(this.tableName);
let records = [];
if(table) {
records = JSON.parse(table);
}
records.push(value);
window.localStorage.setItem(this.tableName, JSON.stringify(records));
}
/**
* Retreives a record from the table
*
* @param key Unique identifier of the record
* @param value The expected value
*
* Example:
* ```js
* let result = storage.select('id', 1);
* ```
*/
select(key: string, value: string): Array<any> {
let records = this.list();
return records.filter(record => record[key] === value);
}
/**
* Returns all records in table
*
* Example:
* ```js
* let result = storage.list();
* ```
*/
list(): Array<any> {
let table = window.localStorage.getItem(this.tableName);
if(table) {
return JSON.parse(table);
} else {
return [];
}
}
/**
* Updates records in table
*
* Example:
* ```js
* this.storage.update([{key: 'name', value: 'James'}], [{key: 'id', value: '1'}]);
* ```
*/
update(values, where) {
let records = this.list();
records.forEach(record => {
where.forEach(w => {
if(record[w.key] === w.value) {
values.forEach(v => {
record[v.key] = v.value;
});
}
});
});
window.localStorage.setItem(this.tableName, JSON.stringify(records));
}
/**
* Clears table of all records
*
* Example:
* ```js
* storage.clear();
* ```
*/
clear() {
window.localStorage.removeItem(this.tableName);
}
} |