utils.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. export const DEFAULT_BOX_OPTIONS = { security: 'private', personal: false };
  2. export const wrapBackend = (backend, siteId) => {
  3. const getBoxId = (userBoxId) => {
  4. return `_${siteId}__${userBoxId}`;
  5. };
  6. const migrationToApply = {
  7. async storeBySiteId(newBoxId) {
  8. const oldBoxId = newBoxId.split('__')[1];
  9. const exists = await backend.getBoxOption(oldBoxId);
  10. // Migrate only previously existing collection
  11. if (!exists) return;
  12. const data = await backend.list(oldBoxId);
  13. for (const item of data) {
  14. await backend.save(newBoxId, item.id, item);
  15. }
  16. },
  17. };
  18. const migrate = async (boxId) => {
  19. const options = (await backend.getBoxOption(boxId)) || {};
  20. const { migrations = [] } = options;
  21. const migrationApplied = [];
  22. for (const key of Object.keys(migrationToApply)) {
  23. if (!migrations.includes(key)) {
  24. await migrationToApply[key](boxId);
  25. migrationApplied.push(key);
  26. }
  27. }
  28. await backend.createOrUpdateBox(boxId, {
  29. ...options,
  30. migrations: Array.from(new Set([...migrations, ...migrationApplied])),
  31. });
  32. };
  33. return {
  34. async checkSecurity(boxId, id, write = false) {
  35. const { security = 'private' } =
  36. (await backend.getBoxOption(getBoxId(boxId))) || {};
  37. switch (security) {
  38. case 'private':
  39. return false;
  40. case 'public':
  41. return true;
  42. case 'readOnly':
  43. return !write;
  44. default:
  45. return false;
  46. }
  47. },
  48. async createOrUpdateBox(boxId, options) {
  49. const result = await backend.createOrUpdateBox(getBoxId(boxId), options);
  50. // Apply migration if any
  51. await migrate(getBoxId(boxId));
  52. return result;
  53. },
  54. async list(boxId, options) {
  55. // find
  56. return await backend.list(getBoxId(boxId), options);
  57. },
  58. // has
  59. /*async has(boxId, id) {
  60. return await backend.has(getBoxId(boxId), id);
  61. },*/
  62. async get(boxId, id) {
  63. return await backend.get(getBoxId(boxId), id);
  64. },
  65. async set(boxId, id, data) {
  66. return await backend.save(getBoxId(boxId), id, data);
  67. },
  68. async save(boxId, id, data) {
  69. return await backend.save(getBoxId(boxId), id, data);
  70. },
  71. async update(boxId, id, data) {
  72. return await backend.update(getBoxId(boxId), id, data);
  73. },
  74. async delete(boxId, id) {
  75. return await backend.delete(getBoxId(boxId), id);
  76. },
  77. };
  78. };