operation.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. const Aspect = {
  3. READ_OPERATION: Symbol('READ_OPERATION'),
  4. WRITE_OPERATION: Symbol('WRITE_OPERATION'),
  5. RETRYABLE: Symbol('RETRYABLE'),
  6. EXECUTE_WITH_SELECTION: Symbol('EXECUTE_WITH_SELECTION')
  7. };
  8. /**
  9. * This class acts as a parent class for any operation and is responsible for setting this.options,
  10. * as well as setting and getting a session.
  11. * Additionally, this class implements `hasAspect`, which determines whether an operation has
  12. * a specific aspect.
  13. */
  14. class OperationBase {
  15. constructor(options) {
  16. this.options = Object.assign({}, options);
  17. }
  18. hasAspect(aspect) {
  19. if (this.constructor.aspects == null) {
  20. return false;
  21. }
  22. return this.constructor.aspects.has(aspect);
  23. }
  24. set session(session) {
  25. Object.assign(this.options, { session });
  26. }
  27. get session() {
  28. return this.options.session;
  29. }
  30. clearSession() {
  31. delete this.options.session;
  32. }
  33. get canRetryRead() {
  34. return true;
  35. }
  36. execute() {
  37. throw new TypeError('`execute` must be implemented for OperationBase subclasses');
  38. }
  39. }
  40. function defineAspects(operation, aspects) {
  41. if (!Array.isArray(aspects) && !(aspects instanceof Set)) {
  42. aspects = [aspects];
  43. }
  44. aspects = new Set(aspects);
  45. Object.defineProperty(operation, 'aspects', {
  46. value: aspects,
  47. writable: false
  48. });
  49. return aspects;
  50. }
  51. module.exports = {
  52. Aspect,
  53. defineAspects,
  54. OperationBase
  55. };