forked from sugarcrm/thorn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetadata-handler.js
237 lines (215 loc) · 7.68 KB
/
metadata-handler.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/*
* Copyright (c) 2017 SugarCRM Inc. Licensed by SugarCRM under the Apache 2.0 license.
*/
let MetadataFetcher = require('./metadata-fetcher.js');
let faker = require('faker');
let MetadataHandler = {
/**
* @property {Object} _metadata Metadata structure.
*
* @private
*/
_metadata: null,
/**
* Generates random values field types.
*
* @param {Object} field Field definitions.
*
* @return {string} Random field value according to type and module.
*/
generateFieldValue(field) {
let val;
let maxLength;
switch (field.type) {
case 'bool': {
val = faker.random.boolean();
break;
}
case 'char':
case 'password':
case 'varchar': {
// this is char in the SQL sense, not the C sense
maxLength = field.len || 30;
maxLength = maxLength > 30 ? 30 : maxLength;
val = faker.random.alphaNumeric(maxLength);
break;
}
case 'currency':
case 'decimal': {
// faker.js has no support for decimal numbers
maxLength = field.len || '5,2';
let [beforeDecimal, afterDecimal] = this._parsePrecision(maxLength);
// For sanity, set the max before decimal to 3 and after to 2
beforeDecimal = beforeDecimal > 3 ? 3 : beforeDecimal;
afterDecimal = afterDecimal > 2 ? 2 : afterDecimal;
// To avoid JS floating point issues, build string and cast as float
val = `${faker.random.number({max: Math.pow(10, beforeDecimal)})}`;
if (afterDecimal > 0) {
val += `.${faker.random.number({max: Math.pow(10, afterDecimal)})}`;
}
val = Number.parseFloat(val);
break;
}
case 'date':
case 'datetime':
case 'datetimecombo': {
val = faker.date.recent(5);
break;
}
case 'email': {
val = faker.internet.exampleEmail('Jack', 'Jackson');
// FIXME: support maximum lengths!
break;
}
case 'enum': {
// for now, we just return an arbitrary random string
val = faker.lorem.word();
break;
}
case 'int': {
maxLength = field.len || 5;
// For sanity, set the max number of digits to 5
maxLength = maxLength > 5 ? 5 : maxLength;
val = faker.random.number({max: Math.pow(10, maxLength)});
break;
}
case 'name': {
val = faker.name.firstName();
break;
}
case 'phone': {
// these are used with callto: URLs
val = faker.phone.phoneNumber().replace(/\D/g, '');
if (field.len) {
val = val.substring(0, field.len);
}
break;
}
case 'text':
case 'longtext': {
val = faker.lorem.paragraph();
break;
}
case 'url': {
val = faker.internet.url();
if (field.len) {
/* the minimum length of an HTTPS URL is 9 ("https://a").
Other protocols could obviously allow shorter ones,
but Faker only supports HTTP(S). So forbid any lengths
shorter than that. */
if (field.len < 9) {
throw new Error('URLs with fewer than 9 characters are not supported.');
}
val = val.substring(0, field.len);
}
break;
}
case 'assigned_user_name':
case 'file':
case 'id':
case 'image':
case 'json':
case 'link':
case 'relate':
case 'team_list':
case 'username':
throw new Error(`Fields of type ${field.type} are not supported. Please define them manually.`);
default:
throw new Error(`Field type ${field.type} is not recognized.`);
}
return val;
},
/**
* Parse an SQL precision specification.
*
* @param {string} prec The precision specification.
*
* @return {number[]} The maximum number of digits expected on
* either end of the decimal point.
* @see https://msdn.microsoft.com/en-us/library/ms187746.aspx
*
* @private
*/
_parsePrecision(prec) {
let [precision, scale] = prec.split(',');
scale = scale || 0;
let afterDecimal = Number.parseInt(scale, 10);
let beforeDecimal = Number.parseInt(precision, 10) - afterDecimal;
return [beforeDecimal, afterDecimal];
},
/**
* Returns the required fields of module.
*
* @param {string} module Module name.
*
* @return {Promise} Promise that resolves to required fields.
*/
getRequiredFields(module) {
let self = this;
if (this._metadata) {
if (!this._metadata[module]) {
throw new Error(`Unrecognized module: ${module}`);
}
return Promise.resolve(this._metadata[module].fields);
}
if (process.env.THORN_METADATA_FILE) {
let fileMetadata = require(process.env.THORN_METADATA_FILE);
fileMetadata = this._patchMetadata(fileMetadata);
this._metadata = fileMetadata;
if (!this._metadata[module]) {
throw new Error(`Unrecognized module: ${module}`);
}
return Promise.resolve(this._metadata[module].fields);
}
return MetadataFetcher.fetch()
.then((metadata) => {
// If metadata has been cached already it means it has been
// patched already too, thus there's no need to re-patch metadata again
if (!self._metadata) {
self._metadata = self._patchMetadata(metadata);
}
if (!self._metadata[module]) {
throw new Error(`Unrecognized module: ${module}`);
}
return self._metadata[module].fields;
});
},
/**
* Clears the cached metadata
*/
clearCachedMetadata() {
this._metadata = null;
},
/**
* Updates the passed in metadata with special cases.
*
* Special cases include:
* Users.user_hash
*
* @param {Object} metadata The metadata to patch.
* @return {Object} The patched metadata.
*
* @private
*/
_patchMetadata(metadata) {
// When we want to log in with a created user, the user_hash
// must be defined. If we want to generate the user_hash automatically,
// the user_hash field must be required.
// Currently OOTB user_hash isn't set as required. If this changes
// in the future, throw warning below. At that point, the patch
// to the User metadata is no longer necessary.
let userHash = {
name: 'user_hash',
type: 'password',
};
if (metadata.Users) {
if (metadata.Users.fields.user_hash) {
console.warn('Users user_hash field is required => true on the Mango side. Skipping metadata patch.');
} else {
metadata.Users.fields.user_hash = userHash;
}
}
return metadata;
},
};
module.exports = MetadataHandler;