Use Proxy to better encapsulate Storage API

⭐️ more front-end technology and knowledge, search subscription number JS bacteria subscription

That sounds good to see the article, the original: davidwalsh. Name/javascript -… Proxy to encapsulate the Storage API, do a layer to provide access to data Proxy layer. Here is a brief translation of the main content of this article.

Packaging Storage

This article mentions that the Proxy syntax can be used to encapsulate sessionStorage, localStorage, and even IndexedDB. You can use a Proxy Proxy to make the API easier to use.

Let’s start with the basic usage of Proxy:

/* const proxy = new Proxy({}, { get: (obj, prop) => { ... }, set: (obj, prop, value) => { ... }, // more props here }); * /

// This basic proxy returns null instead of undefined if the
// property doesn't exist
// If the attribute does not exist, null is returned instead of undefined
const proxy = new Proxy({}, {
  get: (obj, prop) = > {
    return prop in obj ? obj[prop] : null; }});// proxy.whatever => null
Copy the code

Then write an agent to access Storage data:

// storage is the type of the storage API. It can be localStorage or sessionStorage
// prefix belongs to namespace
function getStorage(storage, prefix) {
    // This returns a Proxy instance whose set or GET methods are called to access data
  return new Proxy({}, {
    set: (obj, prop, value) = > {
      obj[prop] = value;
      storage.setItem(`${prefix}.${prop}`, value);
    },
    get: (obj, prop) = > {
      // return obj[prop];
      return storage.getItem(`${prefix}.${prop}`); }}); }// Create an instance of the storage proxy
// Create a Storage Proxy instance through the namespace
const userObject = getStorage(localStorage, "user");

// Set a value in localStorage
// Then manipulate the data by directly accessing the attributes
userObject.name = "David";

// Get the value from localStorage
// It is easy to use deconstruction to get data
const { name } = userObject;
Copy the code

supplement

class Storage {
  constructor(storage, prefix) {
    this.storage = storage;
    this.prefix = prefix;
  }
  getItem(prop) {
    return this.storage.getItem(`The ${this.prefix}.${prop}`);
  }
  setItem(prop, val) {
    return this.storage.setItem(`The ${this.prefix}.${prop}`, val); }}Copy the code

Use class encapsulation to create a Storage instance using the new method and use the get/setItem method. It is more convenient to read data using the property operator after Proxy encapsulation.

Please pay attention to my subscription number, push technical articles about JS irregularly, only talk about technology not gossip 😊