volume-localstorage.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.createVolume = exports.ObjectStore = void 0;
  4. const volume_1 = require("./volume");
  5. const node_1 = require("./node");
  6. class ObjectStore {
  7. constructor(obj) {
  8. this.obj = obj;
  9. }
  10. setItem(key, json) {
  11. this.obj[key] = JSON.stringify(json);
  12. }
  13. getItem(key) {
  14. const data = this.obj[key];
  15. if (typeof data === void 0)
  16. return void 0;
  17. return JSON.parse(data);
  18. }
  19. removeItem(key) {
  20. delete this.obj[key];
  21. }
  22. }
  23. exports.ObjectStore = ObjectStore;
  24. function createVolume(namespace, LS = localStorage) {
  25. const store = new ObjectStore(LS);
  26. const key = (type, id) => `memfs.${namespace}.${type}.${id}`;
  27. class NodeLocalStorage extends node_1.Node {
  28. get Key() {
  29. if (!this._key)
  30. this._key = key('ino', this.ino);
  31. return this._key;
  32. }
  33. sync() {
  34. store.setItem(this.Key, this.toJSON());
  35. }
  36. touch() {
  37. super.touch();
  38. this.sync();
  39. }
  40. del() {
  41. super.del();
  42. store.removeItem(this.Key);
  43. }
  44. }
  45. class LinkLocalStorage extends node_1.Link {
  46. get Key() {
  47. if (!this._key)
  48. this._key = key('link', this.getPath());
  49. return this._key;
  50. }
  51. sync() {
  52. store.setItem(this.Key, this.toJSON());
  53. }
  54. }
  55. return class VolumeLocalStorage extends volume_1.Volume {
  56. constructor() {
  57. super({
  58. Node: NodeLocalStorage,
  59. Link: LinkLocalStorage,
  60. });
  61. }
  62. createLink(parent, name, isDirectory, perm) {
  63. const link = super.createLink(parent, name, isDirectory, perm);
  64. store.setItem(key('link', link.getPath()), link.toJSON());
  65. return link;
  66. }
  67. deleteLink(link) {
  68. store.removeItem(key('link', link.getPath()));
  69. return super.deleteLink(link);
  70. }
  71. };
  72. }
  73. exports.createVolume = createVolume;