Discard localStorage

I am creating an Angular2 library that adds an abstraction layer to localStorage and sessionStorage to add functionality like permission levels and nice and much more. The problem I am facing is that I want to throw errors if other developers try to access localStorage or sessionStorage directly. To ensure the proper use of permissions and other things.

So, for this, basically I want to copy the localStorage and sessionStorage links, and then redefine their functions as follows:

  this.localStorageReference = Object.assign({}, localStorage);
  this.sessionStorageReference = Object.assign({}, sessionStorage);

  const err = "Use the StorageStrategy, not localStorage or sessionStorage.";
  Storage.prototype._setItem = Storage.prototype.setItem;
  Storage.prototype.setItem = function(key, value)
  {
    throw Error(err);
  }

  Storage.prototype._getItem = Storage.prototype.getItem;
  Storage.prototype.getItem = function(key){
    throw Error(err);
  }

Which overrides work fine and throw an error, the problem is that Object.assign doesn't seem to copy what I need. Because when I try to use a link, I don’t have any methods.

this.localStorageReference.setItem(key, obj);

leads to:

TypeError: this.localStorageReference.setItem is not a function

localStorage, . ?

+4
1

Object.keys(localStorage). , . for (let key in localStorage) - , .

, . , "" .

const fakeStorage = ["clear", "setItem", "getItem", "removeItem", /*...*/]
  .map(method => [method, localStorage[method].bind(localStorage)])
  .reduce((obj, [key, value]) => {
    obj[key] = value;
    return obj;
  }, {});

, . , Storage , ( , , ..).

... , ?

+2

Source: https://habr.com/ru/post/1691954/


All Articles