G_lander

My EPIC localStorage wrapper

Mar 22nd, 2020
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. /**
  2. * The localStotrage wrapper class
  3. */
  4. export default class LocalStorageWrapper {
  5. store: Record<string | number, unknown>
  6. /**
  7. * The wrapper class for localStorage
  8. * @param name The name of the key
  9. */
  10. constructor(private name: string) {
  11. this.updateValues(name)
  12. this.store = new Proxy(this.store, {
  13. set: (target, key: string | number, value): boolean => {
  14. const retVal = Reflect.set(target, key, value)
  15. this.writeValues()
  16. return retVal
  17. },
  18. deleteProperty: (target, key): boolean => {
  19. const retVal = Reflect.deleteProperty(target, key)
  20. this.writeValues()
  21. return retVal
  22. },
  23. })
  24. }
  25. /**
  26. * Reads the values from the name
  27. * @param name The key to read from
  28. */
  29. updateValues(name: string): void {
  30. this.store = JSON.parse(localStorage.getItem(name))
  31. }
  32. /**
  33. * Writes store to localstorage
  34. */
  35. writeValues(): void {
  36. localStorage.setItem(this.name, JSON.stringify(this.store))
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment