UNPKG

2.52 kBJavaScriptView Raw
1// Copyright IBM Corp. 2017,2019. All Rights Reserved.
2// Node module: loopback-datasource-juggler
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6'use strict';
7
8const inspect = require('util').inspect;
9
10module.exports = DateString;
11
12/**
13 * A String whose value is a valid representation of a Date.
14 * Use this type if you need to preserve the format of the value and still
15 * check if it's valid.
16 * Example:
17 * ```js
18 * var loopback = require('loopback');
19 * var dt = new loopback.DateString('2001-01-01');
20 *
21 * dt.toString();
22 * // '2001-01-01'
23 * dt._date.toISOString();
24 * // '2001-01-01T00:00:00.000Z'
25 * ```
26 *
27 * You can use this definition on your models as well:
28 * ```json
29 * {
30 * "name": "Person",
31 * "base": "PersistedModel",
32 * "properties": {
33 * "name": {
34 * "type": "string"
35 * },
36 * "dob": {
37 * "type": "DateString",
38 * "required": true
39 * },
40 * },
41 * "validations": [],
42 * "relations": {},
43 * "acls": [],
44 * "methods": {}
45 * }
46 * ```
47 * @class DateString
48 * @param {String} value
49 * @constructor
50 */
51function DateString(value) {
52 if (!(this instanceof DateString)) {
53 return new DateString(value);
54 }
55
56 if (value instanceof DateString) {
57 value = value.when;
58 }
59
60 if (typeof(value) !== 'string') {
61 throw new Error('Input must be a string');
62 }
63
64 Object.defineProperty(this, 'when', {
65 get: () => { return this._when; },
66 set: (val) => {
67 const d = new Date(val);
68 if (isNaN(d.getTime())) {
69 throw new Error('Invalid date');
70 } else {
71 this._when = val;
72 this._date = d;
73 }
74 },
75 });
76
77 this.when = value;
78}
79
80/**
81 * Returns the value of DateString in its original form.
82 * @returns {String} The Date as a String.
83 */
84DateString.prototype.toString = function() {
85 return this.when;
86};
87
88/**
89 * Returns the JSON representation of the DateString object.
90 * @returns {String} A JSON string.
91 */
92DateString.prototype.toJSON = function() {
93 return JSON.stringify({
94 when: this.when,
95 });
96};
97
98DateString.prototype.inspect = function(depth, options) {
99 return 'DateString ' + inspect({
100 when: this.when,
101 _date: this._date,
102 });
103};
104
105if (inspect.custom) {
106 // Node.js 12+ no longer recognizes "inspect" method,
107 // it uses "inspect.custom" symbol as the key instead
108 // TODO(semver-major) always use the symbol key only (requires Node.js 8+).
109 DateString.prototype[inspect.custom] = DateString.prototype.inspect;
110}