read_concern.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import type { Document } from './bson';
  2. /** @public */
  3. export const ReadConcernLevel = Object.freeze({
  4. local: 'local',
  5. majority: 'majority',
  6. linearizable: 'linearizable',
  7. available: 'available',
  8. snapshot: 'snapshot'
  9. } as const);
  10. /** @public */
  11. export type ReadConcernLevel = (typeof ReadConcernLevel)[keyof typeof ReadConcernLevel];
  12. /** @public */
  13. export type ReadConcernLike = ReadConcern | { level: ReadConcernLevel } | ReadConcernLevel;
  14. /**
  15. * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties
  16. * of the data read from replica sets and replica set shards.
  17. * @public
  18. *
  19. * @see https://www.mongodb.com/docs/manual/reference/read-concern/index.html
  20. */
  21. export class ReadConcern {
  22. level: ReadConcernLevel | string;
  23. /** Constructs a ReadConcern from the read concern level.*/
  24. constructor(level: ReadConcernLevel) {
  25. /**
  26. * A spec test exists that allows level to be any string.
  27. * "invalid readConcern with out stage"
  28. * @see ./test/spec/crud/v2/aggregate-out-readConcern.json
  29. * @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#unknown-levels-and-additional-options-for-string-based-readconcerns
  30. */
  31. this.level = ReadConcernLevel[level] ?? level;
  32. }
  33. /**
  34. * Construct a ReadConcern given an options object.
  35. *
  36. * @param options - The options object from which to extract the write concern.
  37. */
  38. static fromOptions(options?: {
  39. readConcern?: ReadConcernLike;
  40. level?: ReadConcernLevel;
  41. }): ReadConcern | undefined {
  42. if (options == null) {
  43. return;
  44. }
  45. if (options.readConcern) {
  46. const { readConcern } = options;
  47. if (readConcern instanceof ReadConcern) {
  48. return readConcern;
  49. } else if (typeof readConcern === 'string') {
  50. return new ReadConcern(readConcern);
  51. } else if ('level' in readConcern && readConcern.level) {
  52. return new ReadConcern(readConcern.level);
  53. }
  54. }
  55. if (options.level) {
  56. return new ReadConcern(options.level);
  57. }
  58. return;
  59. }
  60. static get MAJORITY(): 'majority' {
  61. return ReadConcernLevel.majority;
  62. }
  63. static get AVAILABLE(): 'available' {
  64. return ReadConcernLevel.available;
  65. }
  66. static get LINEARIZABLE(): 'linearizable' {
  67. return ReadConcernLevel.linearizable;
  68. }
  69. static get SNAPSHOT(): 'snapshot' {
  70. return ReadConcernLevel.snapshot;
  71. }
  72. toJSON(): Document {
  73. return { level: this.level };
  74. }
  75. }