processConnectionOptions.js 1.9 KB

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