Source: crdt/CRDTRegistry.ts

  1. /**
  2. * @author Maximilian Kallert <max@refinio.net>
  3. * @author Eduard Reimer <eduard@refinio.net>
  4. * @copyright REFINIO GmbH 2020
  5. * @license CC-BY-NC-SA-2.5; portions MIT License
  6. * @version 1.0.0
  7. */
  8. /**
  9. * This module takes care of registering all CRDT implementations.
  10. *
  11. * Specific algorithms need to be added to CRDTImplementationNames and then in the
  12. * crdtImplementationMap.
  13. * @module
  14. */
  15. import type {CRDTImplementation} from './CRDTImplementation';
  16. import {LWWRegister} from './LWWRegister';
  17. import {LWWSet} from './LWWSet';
  18. import {ObjectCRDT} from './ObjectCRDT';
  19. import {ORRegister} from './ORRegister';
  20. import {ORSet} from './ORSet';
  21. import {ORSetForArrays} from './ORSetForArrays';
  22. export type CRDTImplementationTypes = 'list' | 'set' | 'register' | 'object';
  23. export type CRDTImplementationNames =
  24. | 'LWWRegister'
  25. | 'LWWSet'
  26. | 'ORRegister'
  27. | 'ORSet'
  28. | 'ORSetForArrays';
  29. const crdtImplementationsMap = new Map<
  30. CRDTImplementationTypes | CRDTImplementationNames,
  31. CRDTImplementation
  32. >([
  33. ['list', new ORSetForArrays()],
  34. ['set', new ORSet()],
  35. ['register', new ORRegister()],
  36. ['object', new ObjectCRDT()],
  37. ['LWWRegister', new LWWRegister()],
  38. ['LWWSet', new LWWSet()],
  39. ['ORRegister', new ORRegister()],
  40. ['ORSet', new ORSet()],
  41. ['ORSetForArrays', new ORSetForArrays()]
  42. ]);
  43. /**
  44. * Returns the algorithm for the supplied type or name
  45. * @param {CRDTImplementationTypes} crdtImplementationType
  46. * @param {CRDTImplementationNames} crdtImplementationName
  47. * @returns {CRDTImplementation}
  48. */
  49. export function getCrdtImplementation(
  50. crdtImplementationType: CRDTImplementationTypes,
  51. crdtImplementationName?: CRDTImplementationNames
  52. ): CRDTImplementation {
  53. const crdtImplementation = crdtImplementationsMap.get(
  54. crdtImplementationName ? crdtImplementationName : crdtImplementationType
  55. );
  56. if (crdtImplementation === undefined) {
  57. throw new Error(
  58. `Didn't find ${crdtImplementationName} or its default ${crdtImplementationType} in the CRDT registry.`
  59. );
  60. }
  61. return crdtImplementation;
  62. }