Code coverage report for src/utils.js

Statements: 97.06% (33 / 34)      Branches: 90.91% (20 / 22)      Functions: 100% (7 / 7)      Lines: 97.06% (33 / 34)      Ignored: none     

All files » src/ » utils.js
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 731 1 1 1           1 33 24 4 20 5 15 6     18       1 2     2 3     2   1     1               1 2   2 8 24 64 19   19   19 19 5               2     1        
var _ = require('underscore')
var uuid = require('node-uuid')
var _inflections = require('underscore.inflections')
_.mixin(_inflections)
 
// Turns string to native.
// Example:
//   'true' -> true
//   '1' -> 1
function toNative(value) {
  if (typeof value === 'string') {
    if (value === '' || value.trim() !== value) {
      return value
    } else if (value === 'true' || value === 'false') {
      return value === 'true'
    } else if (!isNaN(+value)) {
      return +value
    }
  }
  return value
}
 
// Return incremented id or uuid
function createId(coll) {
  Iif (_.isEmpty(coll)) {
    return 1
  } else {
    var id = _.max(coll, function(doc) {
      return doc.id
    }).id
 
    if (_.isFinite(id)) {
      // Increment integer id
      return ++id
    } else {
      // Generate string id
      return uuid()
    }
  }
}
 
 
// Returns document ids that have unsatisfied relations
// Example: a comment that references a post that doesn't exist
function getRemovable(db) {
  var removable = []
 
  _(db).each(function(coll, collName) {
    _(coll).each(function(doc) {
      _(doc).each(function(value, key) {
        if (/Id$/.test(key)) {
          var refName = _.pluralize(key.slice(0, -2))
          // Test if table exists
          Eif (db[refName]) {
            // Test if references is defined in table
            var ref = _.findWhere(db[refName], {id: value})
            if (_.isUndefined(ref)) {
              removable.push({name: collName, id: doc.id})
            }
          }
        }
      })
    })
  })
 
  return removable
}
 
module.exports = {
  toNative: toNative,
  createId: createId,
  getRemovable: getRemovable
}