This is the 10th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

background

LocalStorage and sessionStorage are two apis that we use to store data in our daily front-end development. Our daily operations on them, the use of localStorage, sessionStorage is generally direct:

localStorage.setItem(xxx, xxx);
sessionStorage.setItem(xxx, xxx);
localStorage.getItem(xxx);
sessionStorage.getItem(xxx);
Copy the code

Or some students will simply encapsulate it like this:

const getItem = (key) => { const serializedValue = window.localStorage.getItem(key) as any; return JSON.parse(serializedValue); }; const setItem = (key, value) => { if (window && window.localStorage) { window.localStorage.setItem(key, JSON.stringify(value)); }};Copy the code

While this is not a problem to use, it feels like the code is not elegant enough and has recently encapsulated some of the underlying libraries, including the two brothers. Find something interesting. Xiaobian also has some new experiences and ideas to share with you.

function

  • LocalStorage and sessionStorage Settings
  • LocalStorage and sessionStorage
  • Example Delete an item from localStorage or sessionStorage
  • LocalStorage and sessionStorage Delete all storage

purpose

Encapsulate a localStorage, sessionStorage API, to achieve the storage add, delete, change, check.

Source of ideas

If you’ve used Vue2.0, you know the object.defineProperty method. This API is at the heart of Vue responsiveness. It’s used to observe changes in data, but it has some drawbacks:

  • When a new key/value is added to or an existing key/value is deleted from the object type data, it cannot be observed. As a result, when we add or delete a value from the object data, we cannot notify the dependencies and drive the view to update in response.
  • Array change detection is implemented by Vue2.0 through interceptors, which means that any operation on the array prototype can be detected, but the operation on the array index needs to be manually operated.

These problems have been solved in Vue 3.0 with the method Proxy in ES6.

Proxy is used to modify the default behavior of certain operations, which is equivalent to making changes at the language level, so it is a form of “meta programming”, that is, programming a programming language.

Proxy can be understood as that a layer of “interception” is set up before the target object, and the external access to the object must pass this layer of interception first. Therefore, it provides a mechanism to filter and rewrite the external access. The original meaning of the word Proxy is a Proxy, used here to mean that it “proxies” certain operations. Proxy is a natural interceptor and Proxy, so we can also use Proxy to Proxy localStorage, sessionStorage operations. Without further ado, go straight to the code.

implementation

Var proxyStorage = {/ * * * to return to the Storage agent * @ returns Proxy * @ example * proxyStorage getStorageProxy (localStorage, '_') */ getStorageProxy: (storage, prefix) => { if (! storage) return false; const getKey = (prop) => `${prefix}.${String(prop)}`; return new Proxy(new Object(), {/ * * * set storage * @ returns Boolean * @ example * const storageProxy = proxyStorage. GetStorageProxy (localStorage, '_'); * storageProxy.a = 1; */ set(target, prop, value) { target[prop] = value; storage.setItem(getKey(prop), JSON.stringify(value)); return true; }, / * * * for storage * @ returns Boolean * @ example * const storageProxy = proxyStorage. GetStorageProxy (localStorage, '_'); * console.log(storageProxy.a); */ get(_, prop) { return JSON.parse(storage.getItem(getKey(prop)) || ''); }, / delete storage * * * * @ returns Boolean * @ example * const storageProxy = proxyStorage. GetStorageProxy (localStorage, '_'); * delete storageProxy.a; */ deleteProperty(_, prop) { storage.removeItem(getKey(prop)); return true; }, empty storage / * * * * @ returns Boolean * @ example * const storageProxy = proxyStorage. GetStorageProxy (localStorage, '_'); * Object.preventExtensions(storageProxy); */ preventExtensions(target) { Object.preventExtensions(target); storage.clear(); return true; }, query storage / * * * * @ returns Boolean * @ example * const storageProxy = proxyStorage. GetStorageProxy (localStorage, '_'); * 'a' in storageProxy; */ has(target, prop) { try { return !! storage.key(prop); } catch (error) { return false; }}}); }}; var proxyStorageTest = proxyStorage.getStorageProxy(localStorage, '_');Copy the code

Use Proxy to return a localStorage, sessionStorage Proxy object, this Proxy object, set, get, delete, preventExtensions, in and other operations to hijack.

set

Intercepts the setting of the object property, such as storage.foo = v or storage[‘foo’] = v, and returns a Boolean value. Assign a value to the properties of the proxy object, intercept the assignment, and operate on the setItem of the corresponding storage to directly store the value to the corresponding storage.


storage.a = 1;
// or
storage['a'] = 1;
Copy the code

get

Intercepts reading of object properties, such as storage.foo and storage[‘foo’]. Read the property value of the proxy object, intercept the fetching operation, get the corresponding key, operate the getItem of the corresponding storage, and obtain the corresponding value from the corresponding storage.

console.log(storage.a); / / 1Copy the code

deleteProperty

Intercepts the delete storage[propKey] operation and returns a Boolean value. Here intercept is the object delete data operation, internal storage removeItem operation, delete data.

delete proxyStorageTest.a;
Copy the code

preventExtensions

Intercept object.preventExtensions (storage) and return a Boolean value. Intercepting the non-extensible operation of an object, clearing all stored values is performed internally on the corresponding storage.

Object.preventExtensions(proxyStorageTest);
Copy the code

has

Intercepts the propKey in Proxy operation, along with the object’s hasOwnProperty method, and returns a Boolean value. The operation of intercepting the query properties of an object to query whether a certain key exists in the corresponding storage.

'a' in proxyStorageTest;
Copy the code

conclusion

Proxy to the localStorage, sessionStorage operations, encapsulate a simple storage API. Proxy can be used to operate localStorage, sessionStorage, document. Cookie and indexedDB. There are many other uses for Proxy, such as the use of Proxy in Vue 3.0, and others. The point of this article is not to encapsulate a simple API, but to guide you through the idea.

If you think it helps, give it a like.