-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
92 lines (86 loc) · 2.26 KB
/
index.js
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
const Big = require('big.js');
const moment = require('moment');
const timeRegex = /^([0-1]\d|2[0-3]):([0-5]\d):([0-5]\d)$/g;
const bigTransformer = {
from: function(value) {
if (value) {
return new Big(value);
}
return value;
},
to: function(value) {
if (value) {
return value.toString();
}
return value;
}
};
const booleanTransformer = {
from: function(value) {
if (typeof value !== 'undefined' && value !== null) {
return value ? true : false;
}
return value;
},
to: function(value) {
if (value === true) {
return 1;
} else if (value === false) {
return 0;
}
return value;
}
};
const momentTransformer = {
// called on value when fetching from database
from: function(value) {
if (value) {
return moment.utc(value);
}
return value;
},
// called on value before persisting to database
to: function(value) {
if (moment.isMoment(value)) {
try {
return value.utc().toISOString();
} catch (err) {
return moment.utc(value._i).toISOString();
}
}
return value;
}
};
const timeTransformer = {
// called on value when fetching from database
from: function (value) {
if (value && !moment.isMoment(value)) {
if (typeof value === 'string' && value.match(timeRegex)) {
return moment(value, 'HH:mm:ss');
} else {
return moment(value);
}
}
return value;
},
// called on value before persisting to database
to: function (value) {
if (value) {
if (!moment.isMoment(value)){
if (typeof value === 'string' && value.match(timeRegex)) {
return moment(value, 'HH:mm:ss').format('HH:mm:ss');
} else {
return moment(value).format('HH:mm:ss');
}
}
return value.format('HH:mm:ss');
}
return value;
}
};
module.exports = {
bigTransformer,
booleanTransformer,
momentTransformer,
timeTransformer
};