range.js
1.76 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
'use strict';
var Utils = require('../../utils'),
moment = require('moment');
module.exports = {
stringify: function (data) {
if (data === null) return null;
if (!Utils._.isArray(data) || data.length !== 2)
return '';
if (Utils._.any(data, Utils._.isNull))
return '';
if (data.hasOwnProperty('inclusive')) {
if (!data.inclusive)
data.inclusive = [false, false];
else if (data.inclusive === true)
data.inclusive = [true, true];
} else
data.inclusive = [false, false];
Utils._.each(data, function (value, index) {
if (Utils._.isObject(value)) {
if (value.hasOwnProperty('inclusive'))
data.inclusive[index] = !!value.inclusive;
if (value.hasOwnProperty('value'))
data[index] = value.value;
}
});
return (data.inclusive[0] ? '[' : '(') + JSON.stringify(data[0]) + ',' + JSON.stringify(data[1]) +
(data.inclusive[1] ? ']' : ')');
},
parse: function (value, AttributeType) {
if (value === null) return null;
if(typeof AttributeType === 'function') AttributeType = new AttributeType();
AttributeType = AttributeType || '';
var result = value
.slice(1, -1)
.split(',', 2);
if (result.length !== 2)
return value;
result = result
.map(function (value) {
switch (AttributeType.toString()) {
case 'int4range':
return parseInt(value, 10);
case 'numrange':
return parseFloat(value);
case 'daterange':
case 'tsrange':
case 'tstzrange':
return moment(value).toDate();
}
return value;
});
result.inclusive = [(value[0] === '['), (value[value.length - 1] === ']')];
return result;
}
};