All files / mongoose/lib/helpers processConnectionOptions.js

47.82% Statements 11/23
22.72% Branches 5/22
28.57% Functions 2/7
47.82% Lines 11/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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