UNPKG

2.19 kBJavaScriptView Raw
1/**
2 * Module dependencies.
3 */
4
5var _ = require('lodash'),
6 SchemaType = require('../schematype');
7
8/**
9 * Creates a new SchemaDate instance.
10 *
11 * @param {Object} [options]
12 * @api public
13 */
14
15var SchemaDate = module.exports = function(options){
16 SchemaType.call(this, options);
17};
18
19SchemaDate.type = SchemaDate.prototype.type = Date;
20
21/**
22 * Inherits from SchemaType.
23 */
24
25SchemaDate.__proto__ = SchemaType;
26SchemaDate.prototype.__proto__ = SchemaType.prototype;
27
28/**
29 * Checks if the given `value` is a date object.
30 *
31 * @param {any} value
32 * @return {Boolean}
33 * @api public
34 */
35
36SchemaDate.prototype.checkRequired = function(value){
37 return value instanceof Date;
38};
39
40/**
41 * Casts the given `value` to a date object.
42 *
43 * @param {any} value
44 * @return {Date}
45 * @api public
46 */
47
48var cast = SchemaDate.prototype.cast = function(value){
49 if (value == null || value === '') return null;
50 if (value instanceof Date) return value;
51
52 if (value instanceof Number || typeof value === 'number'){
53 return new Date(value);
54 }
55
56 if (!isNaN(+value)){
57 return new Date(+value);
58 }
59
60 var date = new Date(value);
61
62 if (date.toString() !== 'Invalid Date'){
63 return date;
64 } else {
65 return null;
66 }
67};
68
69/**
70 * Transforms a date object into a number.
71 *
72 * @param {Date} value
73 * @return {Number}
74 * @api public
75 */
76
77SchemaDate.prototype.save = function(value){
78 return value.valueOf();
79};
80
81/**
82 * Compares data.
83 *
84 * @param {Date} data
85 * @param {Date} value
86 * @return {Boolean}
87 * @api public
88 */
89
90SchemaDate.prototype.compare = function(data, value){
91 return data.valueOf() === cast(value).valueOf();
92};
93
94SchemaDate.prototype.q$year = function(data, value){
95 return data ? data.getFullYear() == value : false;
96};
97
98SchemaDate.prototype.q$month = function(data, value){
99 return data ? data.getMonth() == value - 1 : false;
100};
101
102SchemaDate.prototype.q$day = function(data, value){
103 return data ? data.getDate() == value : false;
104};
105
106SchemaDate.prototype.u$inc = function(data, value){
107 if (!data) return;
108
109 return new Date(data.valueOf() + +value);
110};
111
112SchemaDate.prototype.u$dec = function(data, value){
113 if (!data) return;
114
115 return new Date(data.valueOf() - +value);
116};
\No newline at end of file