processConnectionOptions.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. const clone = require('./clone');
  3. const MongooseError = require('../error/index');
  4. function processConnectionOptions(uri, options) {
  5. const opts = options ? options : {};
  6. const readPreference = opts.readPreference
  7. ? opts.readPreference
  8. : getUriReadPreference(uri);
  9. const clonedOpts = clone(opts);
  10. const resolvedOpts = (readPreference && readPreference !== 'primary' && readPreference !== 'primaryPreferred')
  11. ? resolveOptsConflicts(readPreference, clonedOpts)
  12. : clonedOpts;
  13. return resolvedOpts;
  14. }
  15. function resolveOptsConflicts(pref, opts) {
  16. // don't silently override user-provided indexing options
  17. if (setsIndexOptions(opts) && setsSecondaryRead(pref)) {
  18. throwReadPreferenceError();
  19. }
  20. // if user has not explicitly set any auto-indexing options,
  21. // we can silently default them all to false
  22. else {
  23. return defaultIndexOptsToFalse(opts);
  24. }
  25. }
  26. function setsIndexOptions(opts) {
  27. const configIdx = opts.config?.autoIndex;
  28. const { autoCreate, autoIndex } = opts;
  29. return !!(configIdx || autoCreate || autoIndex);
  30. }
  31. function setsSecondaryRead(prefString) {
  32. return !!(prefString === 'secondary' || prefString === 'secondaryPreferred');
  33. }
  34. function getUriReadPreference(connectionString) {
  35. const exp = /(?:&|\?)readPreference=(\w+)(?:&|$)/;
  36. const match = exp.exec(connectionString);
  37. return match ? match[1] : null;
  38. }
  39. function defaultIndexOptsToFalse(opts) {
  40. opts.config = { autoIndex: false };
  41. opts.autoCreate = false;
  42. opts.autoIndex = false;
  43. return opts;
  44. }
  45. function throwReadPreferenceError() {
  46. throw new MongooseError(
  47. 'MongoDB prohibits index creation on connections that read from ' +
  48. 'non-primary replicas. Connections that set "readPreference" to "secondary" or ' +
  49. '"secondaryPreferred" may not opt-in to the following connection options: ' +
  50. 'autoCreate, autoIndex'
  51. );
  52. }
  53. module.exports = processConnectionOptions;