UNPKG

10.2 kBJavaScriptView Raw
1/*!
2 * Module requirements.
3 */
4
5'use strict';
6
7const MongooseError = require('../error/index');
8const SchemaDateOptions = require('../options/SchemaDateOptions');
9const SchemaType = require('../schematype');
10const castDate = require('../cast/date');
11const utils = require('../utils');
12
13const CastError = SchemaType.CastError;
14
15/**
16 * Date SchemaType constructor.
17 *
18 * @param {String} key
19 * @param {Object} options
20 * @inherits SchemaType
21 * @api public
22 */
23
24function SchemaDate(key, options) {
25 SchemaType.call(this, key, options, 'Date');
26}
27
28/**
29 * This schema type's name, to defend against minifiers that mangle
30 * function names.
31 *
32 * @api public
33 */
34SchemaDate.schemaName = 'Date';
35
36SchemaDate.defaultOptions = {};
37
38/*!
39 * Inherits from SchemaType.
40 */
41SchemaDate.prototype = Object.create(SchemaType.prototype);
42SchemaDate.prototype.constructor = SchemaDate;
43SchemaDate.prototype.OptionsConstructor = SchemaDateOptions;
44
45/*!
46 * ignore
47 */
48
49SchemaDate._cast = castDate;
50
51/**
52 * Sets a default option for all Date instances.
53 *
54 * ####Example:
55 *
56 * // Make all dates have `required` of true by default.
57 * mongoose.Schema.Date.set('required', true);
58 *
59 * const User = mongoose.model('User', new Schema({ test: Date }));
60 * new User({ }).validateSync().errors.test.message; // Path `test` is required.
61 *
62 * @param {String} option - The option you'd like to set the value for
63 * @param {*} value - value for option
64 * @return {undefined}
65 * @function set
66 * @static
67 * @api public
68 */
69
70SchemaDate.set = SchemaType.set;
71
72/**
73 * Get/set the function used to cast arbitrary values to dates.
74 *
75 * ####Example:
76 *
77 * // Mongoose converts empty string '' into `null` for date types. You
78 * // can create a custom caster to disable it.
79 * const original = mongoose.Schema.Types.Date.cast();
80 * mongoose.Schema.Types.Date.cast(v => {
81 * assert.ok(v !== '');
82 * return original(v);
83 * });
84 *
85 * // Or disable casting entirely
86 * mongoose.Schema.Types.Date.cast(false);
87 *
88 * @param {Function} caster
89 * @return {Function}
90 * @function get
91 * @static
92 * @api public
93 */
94
95SchemaDate.cast = function cast(caster) {
96 if (arguments.length === 0) {
97 return this._cast;
98 }
99 if (caster === false) {
100 caster = v => {
101 if (v != null && !(v instanceof Date)) {
102 throw new Error();
103 }
104 return v;
105 };
106 }
107 this._cast = caster;
108
109 return this._cast;
110};
111
112/**
113 * Declares a TTL index (rounded to the nearest second) for _Date_ types only.
114 *
115 * This sets the `expireAfterSeconds` index option available in MongoDB >= 2.1.2.
116 * This index type is only compatible with Date types.
117 *
118 * ####Example:
119 *
120 * // expire in 24 hours
121 * new Schema({ createdAt: { type: Date, expires: 60*60*24 }});
122 *
123 * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax:
124 *
125 * ####Example:
126 *
127 * // expire in 24 hours
128 * new Schema({ createdAt: { type: Date, expires: '24h' }});
129 *
130 * // expire in 1.5 hours
131 * new Schema({ createdAt: { type: Date, expires: '1.5h' }});
132 *
133 * // expire in 7 days
134 * var schema = new Schema({ createdAt: Date });
135 * schema.path('createdAt').expires('7d');
136 *
137 * @param {Number|String} when
138 * @added 3.0.0
139 * @return {SchemaType} this
140 * @api public
141 */
142
143SchemaDate.prototype.expires = function(when) {
144 if (!this._index || this._index.constructor.name !== 'Object') {
145 this._index = {};
146 }
147
148 this._index.expires = when;
149 utils.expires(this._index);
150 return this;
151};
152
153/*!
154 * ignore
155 */
156
157SchemaDate._checkRequired = v => v instanceof Date;
158
159/**
160 * Override the function the required validator uses to check whether a string
161 * passes the `required` check.
162 *
163 * ####Example:
164 *
165 * // Allow empty strings to pass `required` check
166 * mongoose.Schema.Types.String.checkRequired(v => v != null);
167 *
168 * const M = mongoose.model({ str: { type: String, required: true } });
169 * new M({ str: '' }).validateSync(); // `null`, validation passes!
170 *
171 * @param {Function} fn
172 * @return {Function}
173 * @function checkRequired
174 * @static
175 * @api public
176 */
177
178SchemaDate.checkRequired = SchemaType.checkRequired;
179
180/**
181 * Check if the given value satisfies a required validator. To satisfy
182 * a required validator, the given value must be an instance of `Date`.
183 *
184 * @param {Any} value
185 * @param {Document} doc
186 * @return {Boolean}
187 * @api public
188 */
189
190SchemaDate.prototype.checkRequired = function(value, doc) {
191 if (SchemaType._isRef(this, value, doc, true)) {
192 return !!value;
193 }
194
195 // `require('util').inherits()` does **not** copy static properties, and
196 // plugins like mongoose-float use `inherits()` for pre-ES6.
197 const _checkRequired = typeof this.constructor.checkRequired == 'function' ?
198 this.constructor.checkRequired() :
199 SchemaDate.checkRequired();
200 return _checkRequired(value);
201};
202
203/**
204 * Sets a minimum date validator.
205 *
206 * ####Example:
207 *
208 * var s = new Schema({ d: { type: Date, min: Date('1970-01-01') })
209 * var M = db.model('M', s)
210 * var m = new M({ d: Date('1969-12-31') })
211 * m.save(function (err) {
212 * console.error(err) // validator error
213 * m.d = Date('2014-12-08');
214 * m.save() // success
215 * })
216 *
217 * // custom error messages
218 * // We can also use the special {MIN} token which will be replaced with the invalid value
219 * var min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
220 * var schema = new Schema({ d: { type: Date, min: min })
221 * var M = mongoose.model('M', schema);
222 * var s= new M({ d: Date('1969-12-31') });
223 * s.validate(function (err) {
224 * console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01).
225 * })
226 *
227 * @param {Date} value minimum date
228 * @param {String} [message] optional custom error message
229 * @return {SchemaType} this
230 * @see Customized Error Messages #error_messages_MongooseError-messages
231 * @api public
232 */
233
234SchemaDate.prototype.min = function(value, message) {
235 if (this.minValidator) {
236 this.validators = this.validators.filter(function(v) {
237 return v.validator !== this.minValidator;
238 }, this);
239 }
240
241 if (value) {
242 let msg = message || MongooseError.messages.Date.min;
243 if (typeof msg === 'string') {
244 msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : value.toString()));
245 }
246 const _this = this;
247 this.validators.push({
248 validator: this.minValidator = function(val) {
249 let _value = value;
250 if (typeof value === 'function' && value !== Date.now) {
251 _value = _value.call(this);
252 }
253 const min = (_value === Date.now ? _value() : _this.cast(_value));
254 return val === null || val.valueOf() >= min.valueOf();
255 },
256 message: msg,
257 type: 'min',
258 min: value
259 });
260 }
261
262 return this;
263};
264
265/**
266 * Sets a maximum date validator.
267 *
268 * ####Example:
269 *
270 * var s = new Schema({ d: { type: Date, max: Date('2014-01-01') })
271 * var M = db.model('M', s)
272 * var m = new M({ d: Date('2014-12-08') })
273 * m.save(function (err) {
274 * console.error(err) // validator error
275 * m.d = Date('2013-12-31');
276 * m.save() // success
277 * })
278 *
279 * // custom error messages
280 * // We can also use the special {MAX} token which will be replaced with the invalid value
281 * var max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
282 * var schema = new Schema({ d: { type: Date, max: max })
283 * var M = mongoose.model('M', schema);
284 * var s= new M({ d: Date('2014-12-08') });
285 * s.validate(function (err) {
286 * console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01).
287 * })
288 *
289 * @param {Date} maximum date
290 * @param {String} [message] optional custom error message
291 * @return {SchemaType} this
292 * @see Customized Error Messages #error_messages_MongooseError-messages
293 * @api public
294 */
295
296SchemaDate.prototype.max = function(value, message) {
297 if (this.maxValidator) {
298 this.validators = this.validators.filter(function(v) {
299 return v.validator !== this.maxValidator;
300 }, this);
301 }
302
303 if (value) {
304 let msg = message || MongooseError.messages.Date.max;
305 if (typeof msg === 'string') {
306 msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : value.toString()));
307 }
308 const _this = this;
309 this.validators.push({
310 validator: this.maxValidator = function(val) {
311 let _value = value;
312 if (typeof _value === 'function' && _value !== Date.now) {
313 _value = _value.call(this);
314 }
315 const max = (_value === Date.now ? _value() : _this.cast(_value));
316 return val === null || val.valueOf() <= max.valueOf();
317 },
318 message: msg,
319 type: 'max',
320 max: value
321 });
322 }
323
324 return this;
325};
326
327/**
328 * Casts to date
329 *
330 * @param {Object} value to cast
331 * @api private
332 */
333
334SchemaDate.prototype.cast = function(value) {
335 const castDate = typeof this.constructor.cast === 'function' ?
336 this.constructor.cast() :
337 SchemaDate.cast();
338 try {
339 return castDate(value);
340 } catch (error) {
341 throw new CastError('date', value, this.path, error, this);
342 }
343};
344
345/*!
346 * Date Query casting.
347 *
348 * @api private
349 */
350
351function handleSingle(val) {
352 return this.cast(val);
353}
354
355SchemaDate.prototype.$conditionalHandlers =
356 utils.options(SchemaType.prototype.$conditionalHandlers, {
357 $gt: handleSingle,
358 $gte: handleSingle,
359 $lt: handleSingle,
360 $lte: handleSingle
361 });
362
363
364/**
365 * Casts contents for queries.
366 *
367 * @param {String} $conditional
368 * @param {any} [value]
369 * @api private
370 */
371
372SchemaDate.prototype.castForQuery = function($conditional, val) {
373 if (arguments.length !== 2) {
374 return this._castForQuery($conditional);
375 }
376
377 const handler = this.$conditionalHandlers[$conditional];
378
379 if (!handler) {
380 throw new Error('Can\'t use ' + $conditional + ' with Date.');
381 }
382
383 return handler.call(this, val);
384};
385
386/*!
387 * Module exports.
388 */
389
390module.exports = SchemaDate;