Inital Commit
[oweals/finalsclub.git] / node_modules / mongoose / lib / mongoose / schema / date.js
1
2 /**
3  * Module requirements.
4  */
5
6 var SchemaType = require('../schematype')
7   , CastError = SchemaType.CastError;
8
9 /**
10  * Date SchemaType constructor.
11  *
12  * @param {String} key
13  * @param {Object} options
14  * @api private
15  */
16
17 function SchemaDate (key, options) {
18   SchemaType.call(this, key, options);
19 };
20
21 /**
22  * Inherits from SchemaType.
23  */
24
25 SchemaDate.prototype.__proto__ = SchemaType.prototype;
26
27 /**
28  * Required validator for date
29  *
30  * @api private
31  */
32
33 SchemaDate.prototype.checkRequired = function (value) {
34   return value instanceof Date;
35 };
36
37 /**
38  * Casts to date
39  *
40  * @param {Object} value to cast
41  * @api private
42  */
43
44 SchemaDate.prototype.cast = function (value) {
45   if (value === null || value === '')
46     return null;
47
48   if (value instanceof Date)
49     return value;
50
51   var date;
52
53   // support for timestamps
54   if (value instanceof Number || 'number' == typeof value 
55       || String(value) == Number(value))
56     date = new Date(Number(value));
57
58   // support for date strings
59   else if (value.toString)
60     date = new Date(value.toString());
61
62   if (date.toString() != 'Invalid Date')
63     return date;
64
65   throw new CastError('date', value);
66 };
67
68 /**
69  * Date Query casting.
70  *
71  * @api private
72  */
73
74 function handleSingle (val) {
75   return this.cast(val);
76 }
77
78 function handleArray (val) {
79   var self = this;
80   return val.map( function (m) {
81     return self.cast(m);
82   });
83 }
84
85 SchemaDate.prototype.$conditionalHandlers = {
86     '$lt': handleSingle
87   , '$lte': handleSingle
88   , '$gt': handleSingle
89   , '$gte': handleSingle
90   , '$ne': handleSingle
91   , '$in': handleArray
92   , '$nin': handleArray
93 };
94
95 SchemaDate.prototype.castForQuery = function ($conditional, val) {
96   var handler;
97
98   if (2 !== arguments.length) {
99     return this.cast($conditional);
100   }
101
102   handler = this.$conditionalHandlers[$conditional];
103
104   if (!handler) {
105     throw new Error("Can't use " + $conditional + " with Date.");
106   }
107
108   return handler.call(this, val);
109 };
110
111 /**
112  * Module exports.
113  */
114
115 module.exports = SchemaDate;