-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathprocessor.js
More file actions
76 lines (61 loc) · 1.56 KB
/
Copy pathprocessor.js
File metadata and controls
76 lines (61 loc) · 1.56 KB
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
/**
* Module Dependencies
*/
var _ = require('lodash');
/**
* Processes data returned from a SQL query.
*/
var Processor = module.exports = function Processor(schema) {
this.schema = _.cloneDeep(schema);
return this;
};
/**
* Cast special values to proper types.
*
* Ex: Array is stored as "[0,1,2,3]" and should be cast to proper
* array for return values.
*/
Processor.prototype.cast = function(table, values) {
var self = this;
var _values = _.cloneDeep(values);
Object.keys(values).forEach(function(key) {
self.castValue(table, key, _values[key], _values);
});
return _values;
};
/**
* Cast a value
*
* @param {String} table
* @param {String} key
* @param {Object|String|Number|Array} value
* @param {Object} attributes
* @api private
*/
Processor.prototype.castValue = function(table, key, value, attributes) {
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
switch(type) {
case 'array':
try {
attributes[key] = JSON.parse(value);
} catch(e) {
return;
}
break;
}
};