add storage api

This commit is contained in:
thecodrr
2019-11-27 17:29:10 +05:00
commit 78e3c2fd1f
2 changed files with 48 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
import Convert from "../utils/convert";
class Storage {
constructor(context) {
this.storage = context;
}
async write(key, data) {
await this.storage.write(key, Convert.toString(data));
}
async read(key) {
let data = await this.storage.read(key);
return Convert.fromString(data);
}
clear() {
this.storage.clear();
}
remove(key) {
this.storage.remove(key);
}
}
export default Storage;

View File

@@ -0,0 +1,26 @@
export default class Convert {
static toString(input) {
try {
let type = typeof input;
if (type === "object") return JSON.stringify(input);
return input.toString();
} catch (error) {
return input.toString();
}
}
static fromString(input) {
try {
let firstChar = input[0];
if (firstChar === "[" || firstChar === "{") return JSON.parse(input);
if (parseInt(input) !== NaN) return parseInt(input);
if (parseFloat(input) !== NaN) return parseFloat(input);
if (parseBoolean(input) !== undefined) return parseBoolean(input);
return input;
} catch (error) {
return input;
}
}
}
function parseBoolean(value) {
return value === "true" ? true : value === "false" ? false : undefined;
}