storage-node.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. return new (P || (P = Promise))(function (resolve, reject) {
  4. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  6. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  7. step((generator = generator.apply(thisArg, _arguments || [])).next());
  8. });
  9. };
  10. Object.defineProperty(exports, "__esModule", { value: true });
  11. const fs = require("fs");
  12. class StorageNode {
  13. constructor(id) {
  14. try {
  15. fs.mkdirSync("data");
  16. }
  17. catch (e) {
  18. // ignore
  19. }
  20. const safeId = id.replace(/[^A-Za-z0-9]/g, "");
  21. if (safeId === '') {
  22. throw new Error("must have non-empty id");
  23. }
  24. this.prefix = safeId;
  25. }
  26. getValues() {
  27. return __awaiter(this, void 0, void 0, function* () {
  28. return Object.values(this.getMap());
  29. });
  30. }
  31. get(key) {
  32. return __awaiter(this, void 0, void 0, function* () {
  33. return this.getMap()[key];
  34. });
  35. }
  36. set(key, value) {
  37. return __awaiter(this, void 0, void 0, function* () {
  38. const filename = "data/storage_" + this.prefix;
  39. let map;
  40. try {
  41. const contents = fs.readFileSync(filename, { encoding: 'utf-8' });
  42. map = JSON.parse(contents);
  43. }
  44. catch (e) {
  45. map = {};
  46. }
  47. map[key] = value;
  48. fs.writeFileSync(filename, JSON.stringify(map));
  49. });
  50. }
  51. getMap() {
  52. try {
  53. const filename = "data/storage_" + this.prefix;
  54. const contents = fs.readFileSync(filename, { encoding: 'utf-8' });
  55. return JSON.parse(contents);
  56. }
  57. catch (e) {
  58. return {};
  59. }
  60. }
  61. }
  62. exports.StorageNode = StorageNode;
  63. //# sourceMappingURL=storage-node.js.map