This repository has been archived by the owner on Dec 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
duration.js
50 lines (42 loc) · 1.58 KB
/
duration.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
var ms = require('ms');
var factory = require('../factory');
var TYPE_ERROR = 'should be a duration string (e.g. \"10s\")';
module.exports = factory({
initialize: function(opts) {
this.opts = opts || {};
this.minValue = (this.opts.min != null) ? ms(this.opts.min) : 0;
this.maxValue = (this.opts.max != null) ? ms(this.opts.max) : Number.MAX_VALUE;
this.description = this.opts.description;
if (typeof this.minValue !== 'number') {
throw new Error('Invalid minimum duration: ' + this.opts.min);
}
if (typeof this.maxValue !== 'number') {
throw new Error('Invalid maximum duration: ' + this.opts.max);
}
},
match: function(path, value) {
if (typeof value !== 'string') { return TYPE_ERROR; }
var duration = ms(value);
if (typeof duration !== 'number') { return TYPE_ERROR; }
if (this.opts.min && this.opts.max && (duration < this.minValue || duration > this.maxValue)) {
return 'should be a duration between ' + this.opts.min + ' and ' + this.opts.max;
}
if (this.opts.min && (duration < this.minValue)) {
return 'should be a duration >= ' + this.opts.min;
}
if (this.opts.max && (duration > this.maxValue)) {
return 'should be a duration <= ' + this.opts.max;
}
return null;
},
toJSONSchema: function() {
var schema = {
type: 'string',
pattern: '^((?:\\d+)?\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)$'
};
if (this.description) {
schema.description = this.description;
}
return schema;
}
});