translator.js
2.29 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
77
78
79
80
81
82
83
84
85
86
87
var util = require('../core').util;
var convert = require('./converter');
var Translator = function(options) {
options = options || {};
this.attrValue = options.attrValue;
this.convertEmptyValues = Boolean(options.convertEmptyValues);
this.wrapNumbers = Boolean(options.wrapNumbers);
};
Translator.prototype.translateInput = function(value, shape) {
this.mode = 'input';
return this.translate(value, shape);
};
Translator.prototype.translateOutput = function(value, shape) {
this.mode = 'output';
return this.translate(value, shape);
};
Translator.prototype.translate = function(value, shape) {
var self = this;
if (!shape || value === undefined) return undefined;
if (shape.shape === self.attrValue) {
return convert[self.mode](value, {
convertEmptyValues: self.convertEmptyValues,
wrapNumbers: self.wrapNumbers,
});
}
switch (shape.type) {
case 'structure': return self.translateStructure(value, shape);
case 'map': return self.translateMap(value, shape);
case 'list': return self.translateList(value, shape);
default: return self.translateScalar(value, shape);
}
};
Translator.prototype.translateStructure = function(structure, shape) {
var self = this;
if (structure == null) return undefined;
var struct = {};
util.each(structure, function(name, value) {
var memberShape = shape.members[name];
if (memberShape) {
var result = self.translate(value, memberShape);
if (result !== undefined) struct[name] = result;
}
});
return struct;
};
Translator.prototype.translateList = function(list, shape) {
var self = this;
if (list == null) return undefined;
var out = [];
util.arrayEach(list, function(value) {
var result = self.translate(value, shape.member);
if (result === undefined) out.push(null);
else out.push(result);
});
return out;
};
Translator.prototype.translateMap = function(map, shape) {
var self = this;
if (map == null) return undefined;
var out = {};
util.each(map, function(key, value) {
var result = self.translate(value, shape.value);
if (result === undefined) out[key] = null;
else out[key] = result;
});
return out;
};
Translator.prototype.translateScalar = function(value, shape) {
return shape.toType(value);
};
/**
* @api private
*/
module.exports = Translator;