versioned-storage
Version:
Local storage with versioning.
110 lines (109 loc) • 3.48 kB
JavaScript
function get(key) {
try {
return globalThis.localStorage.getItem(key);
}
catch (_a) {
throw new Error('localStorage not accessible');
}
}
function set(key, value) {
try {
globalThis.localStorage.setItem(key, value);
}
catch (_a) {
throw new Error('localStorage not accessible');
}
}
function remove(key) {
try {
globalThis.localStorage.removeItem(key);
}
catch (_a) {
throw new Error('localStorage not accessible');
}
}
function clear() {
try {
globalThis.localStorage.clear();
}
catch (_a) {
throw new Error('localStorage not accessible');
}
}
/**
* A class that can be instantiated into a storage with a specific name and version.
* Type T stands for the type of the value that is stored in the storage. It has to be serializable to JSON.
*/
var Storage = /** @class */ (function () {
/**
* Create or retrieve the storage with the given name and version.
* If the version is omitted, it will use the existing version of the storage with the given name.
* If there is no existing storage with the given name, it will throw an error.
* @param name Name of the storage.
* @param version Version of the storage. It has to be a positive integer.
*/
function Storage(name, version) {
if (version !== undefined) {
var parsedVersion = parseInt("".concat(version), 10);
if (!parsedVersion || parsedVersion <= 0) {
throw new Error('version has to be a positive integer');
}
this.name = name;
this.version = parsedVersion;
var previousVersion = parseInt("".concat(get(name)), 10) || 0;
if (parsedVersion > previousVersion) {
remove("".concat(name, ":").concat(previousVersion));
set(name, version.toString(10));
}
}
else {
var existingVersion = parseInt("".concat(get(name)), 10) || 0;
if (!existingVersion) {
throw new Error("There is no existing storage named ".concat(name));
}
this.name = name;
this.version = existingVersion;
}
}
/**
* Read the value from the storage.
* @returns The value that is stored in the storage. If there is no value, it returns null.
*/
Storage.prototype.read = function () {
var key = "".concat(this.name, ":").concat(this.version);
var jsonString = get(key);
var value = null;
if (jsonString) {
try {
value = JSON.parse(jsonString);
}
catch (_a) {
// Remove corrupted item
remove(key);
}
}
return value;
};
/**
* Write the value to the storage.
* @param value The value to be stored in the storage.
*/
Storage.prototype.write = function (value) {
var key = "".concat(this.name, ":").concat(this.version);
var jsonString = JSON.stringify(value);
if (jsonString === undefined) {
remove(key);
}
else {
set(key, jsonString);
}
};
/**
* Reset all storages. (It even wipes out other localStorage content that are not written by this class.)
*/
Storage.reset = function () {
clear();
};
return Storage;
}());
export { Storage };