-
Notifications
You must be signed in to change notification settings - Fork 0
API Documentation
-
storage-js - this library, which allows instantiation of storage APIs
-
storage api - the resultant function object which will provide flexible and advanced methods for interacting with your storage medium
-
storage method - a collection of functions for handling very low-level and simple operations on your storage medium
-
storage medium - the object which stores your data, such as localStorage and sessionStorage
To get started with the storage api, you should first instantiate your storage method. A number of methods come pre-defined with storage-js, but you can also create your own.
Storage-js comes with following storage methods:
-
local - stores data in localStorage
-
session - stores data in sessionStorage
-
page - stores data in a private variable (a pre-defined custom storage method) so it's good for the life of the page
To start:
var local = storage("local");
var session = storage("session");
var page = storage("page");
You may use as many different storage methods as you need, you may even instantiate multiple APIs to the same storage method if need be.
A custom storage method should have access to a data object, whether it's localStorage, sessionStorage, or a primitive javascript object, which will store string values by a string key. By default, the storage api uses json to encode all values to json strings for storage, then decodes them upon retrieval so that other data types may be used.
Your storage method should resemble the following. If any method is missing, storage-js will attempt to use the corresponding method from its default storage method, but relying on this is ill-advised since the "default" method may change.
var customStorage = (function() {
var data = {},
// reserve fresh copy so the key can be overwritten later without breaking function
hasOwnProperty = data.hasOwnProperty;
return storage({
"get": function(k) {
var has = hasOwnProperty.call(data, k);
return has ? data[k] : undefined;
},
"all": function() {
var all = {};
for ( k in data ) {
if ( hasOwnProperty.call(data, k) ) {
all[k] = data[k];
}
}
return all;
},
"set": function(k, v) {
data[k] = v;
},
"remove": function(k) {
delete data[k];
},
"clear": function() {
for ( k in data ) {
if ( hasOwnProperty.call(data, k) ) {
delete data[k];
}
}
},
"decode": function(v) {
return v;
},
"encode": function(v) {
return v;
}
});
})();
customStorage.set("key","value");
The storage object comes with a number of methods that can be utilized
- storageMethodName = a predefined storage method name, such as local, session, or page
Instantiates a storage api using a pre-defined storage method.
var session = storage("session");
session.set("myKey", "value");
- storageMethodObject = a custom storage method object
Instantiates a storage api using a custom storage method.
var data = {},
// reserve fresh copy so the key can be overwritten later without breaking function
hasOwnProperty = data.hasOwnProperty,
storageMethod = {
"get": function(k) {
var has = hasOwnProperty.call(data, k);
return has ? data[k] : undefined;
},
"all": function() {
var all = {};
for ( k in data ) {
if ( hasOwnProperty.call(data, k) ) {
all[k] = data[k];
}
}
return all;
},
"set": function(k, v) {
data[k] = v;
},
"remove": function(k) {
delete data[k];
},
"clear": function() {
for ( k in data ) {
if ( hasOwnProperty.call(data, k) ) {
delete data[k];
}
}
},
"decode": function(v) {
return v;
},
"encode": function(v) {
return v;
}
};
Utility function which returns true if the value is an array, helpful for supporting both array and string inputs in the storage API functions
storage.isArray([]); // true
storage.isArray({}); // false
Utility function which returns true if the value can be used as a key by the storage API functions. The storage API currently supports strings and arrays of strings (for nested lookups). This function is generally followed by storage.makeArray(value) so that all inputs can be processed a single way whether they come in as arrays or not.
storage.isKey("key"); // true
storage.isKey(["path","to","key"]); // true
storage.isKey(1); // false
Utility function which returns true if its an array and every value of the array is a valid key (uses storage.isKeySimple(value) to make the determination).
storage.isKeyArray(["path","to","key"]); // true
storage.isKeyArray([1,2]); // false
Utility function which returns true if the given value is a key that the storage API can support. It currently supports any string, but restrictions may get added or more values may be supported in the future or via custom implementations.
storage.isKeySimple("key"); // true
storage.isKeySimple(1); // false
Utility function which returns true if the given object is an object of key/value pairs -- note: this does not check if the keys on the object are valid keys.
storage.isKeyValueObject({"key","value"}); // true
storage.isKeyValueObject({}); // true
storage.isKeyValueObject([]); // false
var num = 1, obj = {}; obj[num] = 1;
storage.isKeyValueObject(obj); // true - does not restrict the type of key
Utility function which will convert the given value into an array if it's not already one. This is helpful for functions which may take either a single value or array of values as their input.. after checking that the input is valid, it can be made into an array and then processed without having separate processing paths for array and non-array values.
var key = "myKey", i, l;
if ( storage.isKey(key) ) {
key = storage.makeArray(key);
for ( i = 0, l = key.length; i < l; i++ ) {
// process key[i]
}
}
- json = a valid json string
Decodes the given json string into a value.
This method may be overwritten to change or enchance how the storage lib encodes JSON.
storage.decodeJSON("{\"key\":\"value\"}"); // { "key": "value" }
- value = any non-function value
Encodes the given value as a JSON string.
This method may be overwritten to change or enhance how the storage lib encodes JSON.
storage.encodeJSON({key:"value"}); // "{\"key\":\"value\"}"
Disables logging to the console (if supported by your browser). Logging is off by default.
Enables logging to the console (if supported by your browser). This can be helpful when developing code or trying to figure out why storage-js isn't behaving as you'd expect. It should not be turned on in a production environment since it can be rather verbose.
Reports an error to the console (if supported by your browser). This does not require logging to be on.
This function may be overwritten to handle error reporting in a different way (such as throwing or alerting the error). Keep in mind that the function takes any number of arguments so you'll need to concatenate them sensibly.
storage.error("Unable to convert value to json, value given:", value);
Logs a debug-level message to the console (if supported by your browser and if logging is enabled). It is recommended that a single function only log a single message, if any. Messages should be quick and easy to generate since the javascript engine still interprets all arguments even if logging is turned off.
storage.log("myFunc: got inputs", input1, input2, input3, "returning", returnValue);
The base function of the storage API may be used as a short-hand for the most common usages of the API. Refer to their sections for more detail and examples.
var session = storage("session");
session(); // calls session.get();
session("key"); // calls session.get(key);
session("key", "value"); // calls session.set(key, value);
Clears the entire storage media of all keys. Use this with caution.
var session = storage("session");
session.clear();
session.get(); // Returns {}
Clears the given key
var session = storage("session");
sesion.clear("key");
session.get("key"); // Returns undefined
Traverses the first key in the array as if it were an object, ultimately clearing the value of the last key. If any traversed key is not an object, it will be set to an empty object and the previous value will be lost.
var session = storage("session");
session.set("person", "bob");
session.clear(["person", "name"]); // clears name but forces person to be an object
session.get("person"); // Returns {}
Returns an object representing the entire storage media
var session = storage("session");
session.clear();
session.set("key", "value");
session.set("key2", "value");
session.get(); // Returns { "key": "value", "key2": "value" }
Returns the value at the given key.
var session = storage("session");
session.set("key", "value");
session.set("key2", "value2");
session.get("key"); // Returns "value"
Returns the value at the given key. If the key is undefined, it returns the default value
var session = storage("session");
session.clear("key");
session.get("key", "my default value"); // Returns "my default value"
Traverses the first key in the array as if its an object, ultimately returning the value at the last key.
var session = storage("session");
session.set("person", { "name": { "first": "John", "last": "Doe" }, "age": 20 });
session.get(["person", "name", "first"]); // Returns "John"
session.get(["person", "height"]); // Returns undefined
Sets the entire storage media to the new object, removing any previous keys that may have been set. Note that calling .set({}) is equivalent to calling .clear(). Calling .set() with no parameters is an invalid call.
var session = storage("session");
session.set("key", "value");
session.set({ "person": { "name": { "first": "John", "last": "Doe" }, "age": 20 } });
session.get("key"); // Returns undefined
session.get(["person", "name"]); // Returns { "first": "John", "last": "Doe" }
Sets the given key to the given value.
var session = storage("session");
session.set("key", "value");
session.get("key"); // Returns "value"
Clears the given key. Note that this is equivalent to calling .clear(key). Also note that not passing a value is considered an invalid call.
var session = storage("session");
session.set("key", undefined);
session.get("key"); // Returns undefined
Traverses the first key in the array as if it were an object, ultimately setting the value of the last key to the given value. If any traversed key is not an object, it will be set to an empty object and the previous value will be lost.
var session = storage("session");
session.set({ "person": { "name": { "first": "John", "last": "Doe" }, "age": 20 } });
session.get(["person", "name", "first"]); // Returns "John"
session.set(["person", "name", "first"], "Jane");
session.get(["person", "name", "first"]); // Returns "Jane"
session.set("key", "value");
session.set(["key", "subkey"], "subvalue"); // converts key to an object
session.get("key"); // Returns { "subkey": "subvalue" }