all files / app/services/ conversionService.js

79.05% Statements 166/210
74.82% Branches 104/139
79.63% Functions 43/54
79.05% Lines 166/210
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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400         23× 23× 23× 45×                                 31× 31× 31× 31× 31×     65× 65× 65× 65× 65× 65×     65× 11×                         65×   36×     36×       36×   36×                                                     17×   17×   15×     15×   65× 29× 29× 29×       27×                                                                                         16× 16×     16×       11×               16×   16× 16× 15×   16× 68× 68× 68× 68× 68× 67×     64×   58× 29× 29× 29×     29×     16×                                   16× 16×     11× 11× 11×             22× 22×                                                                                                                                      
var async = require('async')
var SALT_WORK_FACTOR = 10
var optional = function (module) {
  try {
    return require(module)
  } catch (e) {
  }
}
var path = require('path')
var mongoose = require(path.resolve('node_modules', 'mongoose'))
var bcrypt = optional(path.resolve('node_modules', 'bcrypt'))
 
var compile = function (type) {
  var populate = type.populate = []
  type.hasNested = false
  async.each(type.fields, function (field, cb) {
    if (field.type && field.type.typeName && field.typeName !== 'TypeField') {
      type.hasNested = true
      populate.push({
        path: field.domainName,
        model: field.type.typeName,
        select: field.type.fields.join(' ')
      })
      compile(field.type)
      cb()
    }
  })
}
var converter = module.exports = {
  obscure: function (data, cb) {
    return bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
      if (err) {
        return cb(err)
      }
      bcrypt.hash(data, salt, cb)
    })
  },
  Type: function Type (typeName, fields, options) {
    this.typeName = typeName
    this.fields = fields
    this.hasId = options.hasId
    this.keys = options.keys
    this.discriminator = options.discriminator
  },
  Field: function Field (dtoName, domainName, typeName, type, meta) {
    this.typeName = typeName
    this.dtoName = dtoName
    this.domainName = domainName
    this.type = type
    this.meta = meta || {}
    this.toString = function () {
      return domainName
    }
    this.valueToDto = function (data, cb) {
      switch (typeName) {
        case 'AssociationEnd':
        case 'EntityReferenceField':
        case 'TypeField':
          Iif (data == null) {
            return cb(null, null)
          } else Iif (data._id) {
            return cb(null, data._id)
          } else {
            return cb(null, data)
          }
        default:
          Iif (meta && meta.obscured) {
            return cb(null, null)
          }
          return cb(null, data)
      }
    }
    this.valueFromDto = function (data, cb) {
      // only set if data present (you are changing it).
      Iif (this.meta.obscured && data) {
        return converter.obscure(data, cb)
      }
      var dateParse = function (data) {
        if (data instanceof Date) {
          return data
        } else Iif (typeof data === 'string') {
          return new Date(data)
        }
        return data
      }
      var mParseInt = function (v) {
        return parseInt(v)
      }
      switch (typeName) {
        case 'BooleanField':
          var i = parseInt(data)
          Iif (!data) {
            return cb(null, false)
          } else Iif (!isNaN(i)) {
            return cb(null, !!i)
          } else {
            var b = data.toString().toLowerCase() === 'true'
            return cb(null, b)
          }
        case 'DateField':
          Eif (Array.isArray(data)) {
            return cb(null, data.map(dateParse))
          } else {
            return cb(null, dateParse(data))
          }
        case 'NumericField':
        case 'PriceField':
        case 'Amountield':
          Eif (Array.isArray(data)) {
            return cb(null, data.map(parseFloat))
          } else if (isNaN(data)) {
            return cb(null, parseFloat(data))
          } else {
            return cb(null, data)
          }
        case 'IntegerField':
        case 'CountField':
          Eif (Array.isArray(data)) {
            return cb(null, data.map(mParseInt))
          } else if (isNaN(data)) {
            return cb(null, parseInt(data))
          } else {
            return cb(null, data)
          }
        case 'AssociationEnd':
        case 'EntityReferenceField':
          Iif (data == null) {
            return cb(null, null)
          } else if (data._id) {
            return cb(null, data._id)
          } else {
            return cb(null, data)
          }
      }
      return cb(null, data)
    }
    this.queryFrom = function (value, cb) {
      var that = this
      this.valueFromDto(value, function (ignoreErr, value) {
        if ((that.typeName === 'StringField' || that.typeName === 'ShortIdField' || //
        ((that.typeName === 'AssociationEnd' || that.typeName === 'EntityReferenceField') && !that.type)) && //
        value.match && value.match(/^\/.*\/$/)) {
          cb(null, new RegExp(value.substr(1, value.length - 2)))
        } else {
          cb(null, value)
        }
      })
    }
  },
  types: {},
  toDto: function (typeName, domain, callback) {
    converter.doToDto(converter.types[ typeName ], domain, callback)
  },
  fromDto: function (typeName, dto, callback) {
    converter.doFromDto(converter.types[ typeName ], dto, callback)
  },
  toQuery: function (typeName, dto, callback) {
    converter.doToQuery(converter.types[ typeName ], dto, {}, '', callback)
  },
  doToDto: function (type, domain, callback) {
    if (domain == null) {
      return callback()
    }
    Iif (type == null) {
      return callback(null, domain)
    }
    if (type.hasNested) {
      return mongoose.model(type.typeName).populate(domain, type.populate, function (err, domain) {
        Iif (err) {
          callback(err)
        } else {
          converter.doToDtoPossiblyArray(type, domain, callback)
        }
      })
    } else {
      return converter.doToDtoPossiblyArray(type, domain, callback)
    }
  },
  doFromDto: function (type, dto, callback) {
    if (dto instanceof Array) {
      return async.mapSeries(dto, function (elem, cb) {
        converter.doFromDtoSingle(type, elem, cb)
      }, callback)
    } else {
      return converter.doFromDtoSingle(type, dto, callback)
    }
  },
  doToQuery: function (type, dto, query, path, callback) {
    if (dto instanceof Array) {
      var index = 0
      return async.mapSeries(dto, function (elem, cb) {
        // XXX adding and removing the .index is probably going to confuse
        // people
        converter.doToQuerySingle(type, elem, query, path + ((dto.length > 1) ? '.' + (index++) + '.' : '.'), cb)
      }, function (err) {
        callback(err, query)
      })
    } else {
      return converter.doToQuerySingle(type, dto, query, path, function (err) {
        callback(err, query)
      })
    }
  },
  doFromDtoSingle: function (type, dto, callback) {
    Iif (dto == null) {
      return callback(null, null)
    }
    // any type!?
    Iif (!type) {
      return callback(null, dto)
    }
    var domain = type.typeName ? new (mongoose.models[ type.typeName ])() : {}
    Iif (dto._id) {
      domain._id = dto._id
    }
    return async.each(type.fields, function (field, cb) {
      var value = dto[ field.dtoName ]
      Iif (field.meta.obscured && value == null) {
        delete domain[ field.domainName ]
        return cb()
      } else if (field.type) {
        if (typeof value === 'object' && !(value instanceof mongoose.Types.ObjectId)) {
          converter.doFromDto(field.type, value, function (err, data) {
            domain[ field.domainName ] = data
            return cb(err)
          })
        } else {
          domain[ field.domainName ] = value
          cb()
        }
      } else if (value !== undefined) {
        return field.valueFromDto(value, function (err, value) {
          domain[ field.domainName ] = value
          return cb(err)
        })
      } else {
        cb()
      }
    }, function (err) {
      return callback(err, domain)
    })
  },
  doToQuerySingle: function (type, dto, query, path, callback) {
    Iif (dto == null) {
      return callback(null, query)
    } else Eif (type != null) {
      if (dto._id && path.length) {
        query[ path.replace(/\.$/, '') ] = dto._id
      } else if (dto._id) {
        query._id = dto._id
      }
      return async.each(type.fields, function (field, cb) {
        var value = dto[ field.dtoName ]
        var name = type.keys[ field.domainName ] ? '_id' : field.domainName
        var nestType = field.type
        var fields = typeof value === 'object' ? Object.keys(value).join(',') : ''
        if (fields.match(/(^\$)|(,\$)/)) {
          query[ path + name ] = value
          return cb()
        } else if (value instanceof Array && nestType) {
          converter.doToQuery(nestType, value, query, path + name, function (err) {
            return cb(err)
          })
        } else {
          if (typeof value === 'object' && nestType) {
            return converter.doToQuerySingle(nestType, value, query, path + name + '.', function (err) {
              return cb(err)
            })
          } else if (value != null) {
            return field.queryFrom(value, function (err, value) {
              query[ path + name ] = value
              return cb(err)
            })
          }
          return cb()
        }
      }, function (err) {
        return callback(err, query)
      })
    } else {
      callback()
    }
  },
  doToDtoPossiblyArray: function (type, domains, callback) {
    if (domains instanceof Array) {
      var dtos = []
      return async.eachSeries(domains, function (domain, cb) {
        converter.doToDtoSingle(type, domain, function (err, data) {
          dtos.push(data)
          return cb(err)
        })
      }, function (err) {
        return callback(err, dtos)
      })
    } else {
      return converter.doToDtoSingle(type, domains, callback)
    }
  },
  doToDtoSingle: function (type, domain, callback) {
    var dto = {}
    var fields = type.fields
    Iif (domain == null) {
      return callback(null)
    }
    if (domain._id) {
      dto._id = domain._id
    }
    if (domain.__t) {
      dto.__t = domain.__t
    }
    return async.each(fields, function (field, cb) {
      var fieldData = domain[ field.domainName ]
      if (field.type) {
        converter.doToDto(field.type, fieldData, function (err, data) {
          dto[ field.dtoName ] = data
          return cb(err)
        })
      } else {
        return field.valueToDto(fieldData, function (err, value) {
          dto[ field.dtoName ] = value
          return cb(err)
        })
      }
    }, function (err) {
      return callback(err, dto)
    })
  },
  registerType: function (name, type) {
    converter.types[ name ] = type
    compile(type)
  },
  /**
   * Sandwiches work between DTO conversions. The algorithm is as follows.
   * <ul>
   * <li>The given DTO is converted to the given domain object given by
   * <code>type</code>.</li>
   * <li>If conversion fails, <code>cb</code> is immediately called with the
   * error.</li>
   * <li>If conversion succeeds, <code>fn</code> is called with the converted
   * domain object and a completion callback of the form
   * <code>function(err, domainOut)</code>.</li>
   * <li>If <code>fn</code> fails, then the given callback should be invoked
   * with the error.</li>
   * <li>If <code>fn</code> succeeds, then the given callback should be
   * invoked with a falsey error value and the desired outbound domain object.</li>
   * <li>The outbound domain object is converted back to a DTO and
   * <code>cb</code> is called with error (if there was one) and the outbound
   * dto (if there was no error).</li>
   * </ul>
   *
   * @param type
   *          The fully qualified name of the type used by the converter.
   * @param dtoIn
   *          The inbound data as a DTO.
   * @param fn
   *          A function representing the domain work to be done. Signature is
   *          <code>function(domainIn, callback)</code> where callback is of
   *          the form <code>function(err, domainOut)</code>. The function
   *          <code>fn</code> must call <code>callback</code> to signal
   *          completion of work, passing an error if one occurred or a falsey
   *          value and the domain object to be converted to a DTO, if an error
   *          didn't occur.
   * @param cb
   *          A completion callback of the form <codeLfunction(err, dtoOut)</code>
   *          where <code>dtoOut</code> is the result of converting the domain
   *          object given to <code>fn</code>'s callback.
   */
  sandwich: function (type, dtoIn, fn, cb) {
    converter.from(type, dtoIn, function (errIn, domainIn) {
      if (errIn) {
        return cb(errIn)
      }
      fn(domainIn, function (errFn, domainOut) {
        if (errFn) {
          return cb(errFn)
        }
        converter.to(type, domainOut, function (errOut, dtoOut) {
          cb(errOut, dtoOut)
        })
      })
    })
  }
}
converter.Type.prototype = {
  find: function (query, callback) {
    var that = this
    mongoose.model(that.typeName).find(query, function (ignoredErr, data) {
      converter.doToDto(that, data, callback)
    })
  },
  findOne: function (query, callback) {
    var that = this
    mongoose.model(that.typeName).findOne(query, function (ignoredErr, data) {
      converter.doToDto(that, data, callback)
    })
  }
}
converter.to = converter.toDto
converter.from = converter.fromDto