All files / mongoose/lib/helpers/populate getVirtual.js

2.56% Statements 1/39
0% Branches 0/30
0% Functions 0/3
2.7% Lines 1/37

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 67 68 69 70 71 72 73    1x                                                                                                                                            
'use strict';
 
module.exports = getVirtual;
 
/*!
 * ignore
 */
 
function getVirtual(schema, name) {
  if (schema.virtuals[name]) {
    return { virtual: schema.virtuals[name], path: void 0 };
  }
 
  const parts = name.split('.');
  let cur = '';
  let nestedSchemaPath = '';
  for (let i = 0; i < parts.length; ++i) {
    cur += (cur.length > 0 ? '.' : '') + parts[i];
    if (schema.virtuals[cur]) {
      if (i === parts.length - 1) {
        return { virtual: schema.virtuals[cur], path: nestedSchemaPath };
      }
      continue;
    }
 
    if (schema.nested[cur]) {
      continue;
    }
 
    if (schema.paths[cur] && schema.paths[cur].schema) {
      schema = schema.paths[cur].schema;
      const rest = parts.slice(i + 1).join('.');
 
      if (schema.virtuals[rest]) {
        if (i === parts.length - 2) {
          return {
            virtual: schema.virtuals[rest],
            nestedSchemaPath: [nestedSchemaPath, cur].filter(v => !!v).join('.')
          };
        }
        continue;
      }
 
      if (i + 1 < parts.length && schema.discriminators) {
        for (const key of Object.keys(schema.discriminators)) {
          const res = getVirtual(schema.discriminators[key], rest);
          if (res != null) {
            const _path = [nestedSchemaPath, cur, res.nestedSchemaPath].
              filter(v => !!v).join('.');
            return {
              virtual: res.virtual,
              nestedSchemaPath: _path
            };
          }
        }
      }
 
      nestedSchemaPath += (nestedSchemaPath.length > 0 ? '.' : '') + cur;
      cur = '';
      continue;
    }
 
    if (schema.discriminators) {
      for (const discriminatorKey of Object.keys(schema.discriminators)) {
        const virtualFromDiscriminator = getVirtual(schema.discriminators[discriminatorKey], name);
        if (virtualFromDiscriminator) return virtualFromDiscriminator;
      }
    }
 
    return null;
  }
}