diff --git a/lib/processor.js b/lib/processor.js index 846fe72..4129b39 100644 --- a/lib/processor.js +++ b/lib/processor.js @@ -36,48 +36,41 @@ Processor.prototype.cast = function(table, values) { /** * Cast a value * + * @param {String} table * @param {String} key - * @param {Object|String|Integer|Array} value - * @param {Object} schema + * @param {Object|String|Number|Array} value + * @param {Object} attributes * @api private */ Processor.prototype.castValue = function(table, key, value, attributes) { - - var self = this; - var identity = table; - var attr; - - // Check for a columnName, serialize so we can do any casting - Object.keys(this.schema[identity].attributes).forEach(function(attribute) { - if(self.schema[identity].attributes[attribute].columnName === key) { - attr = attribute; - return; - } - }); - - if(!attr) attr = key; - - // Lookup Schema "Type" - if(!this.schema[identity] || !this.schema[identity].attributes[attr]) return; - var type; - - if(!_.isPlainObject(this.schema[identity].attributes[attr])) { - type = this.schema[identity].attributes[attr]; - } else { - type = this.schema[identity].attributes[attr].type; + var _schema = this.schema[table]; + if (!_schema) return; + + // Cache mappings of column names to attribute names to boost further castings + if (!_schema._columns) { + _schema._columns = {}; + _.each(_schema.attributes, function(attr, attrName) { + _schema._columns[attr.columnName || attrName] = attrName; + }); } + var attr = _schema._columns[key]; + if (!_schema.attributes[attr]) return; + var type = _.isPlainObject(_schema.attributes[attr]) + ? _schema.attributes[attr].type + : _schema.attributes[attr]; if(!type) return; // Attempt to parse Array - if(type === 'array') { - try { - attributes[key] = JSON.parse(value); - } catch(e) { - return; - } + switch(type) { + case 'array': + try { + attributes[key] = JSON.parse(value); + } catch(e) { + return; + } + break; } - };