-
Notifications
You must be signed in to change notification settings - Fork 1
/
simpleschema.js
454 lines (379 loc) · 14.3 KB
/
simpleschema.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/*
Copyright (C) 2013 Tony Mobily
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
[ ] Write tests
*/
const CircularJSON = require('circular-json')
const SimpleSchema = class {
constructor (structure, options) {
this.structure = structure
this.options = options || {}
}
// Built-in types
// definition, value, fieldName, options, failedCasts
noneType (p) {
return p.value
}
stringType (p) {
if (typeof p.value === 'undefined' || p.value === null) return ''
// No toString() available: failing to cast
if (typeof (p.value.toString) === 'undefined') {
throw this._typeError(p.fieldName)
}
// Return cast value, trimmed by default (unless noTrim is passed to the definition)
const r = p.value.toString()
return p.definition.noTrim ? r : r.trim()
}
blobType (p) {
return p.value
}
numberType (p) {
if (typeof (p.value) === 'undefined') return 0
// If Number() returns NaN, fail
const r = Number(p.value)
if (isNaN(r)) {
throw this._typeError(p.fieldName)
}
// Return cast value
return r
}
// This is like "number", but it will set timestamp as NULL for empty strings
timestampType (p) {
// If Number() returns NaN, fail
const r = Number(p.value)
if (isNaN(r)) {
throw this._typeError(p.fieldName)
}
// Return null (if allowed to be null)
if (!r && p.computedOptions.canBeNull) return null
// Return cast value
return r
}
dateTimeType (p) {
if (!Number(p)) return null
// If new Date() returns NaN, date was not correct, fail
const d = new Date(p.value)
if (isNaN(d)) {
throw this._typeError(p.fieldName)
}
// Inspired by https://stackoverflow.com/questions/58249596/how-to-insert-date-into-mysql-datetime-column-from-angular-using-node-js
// But needs checking/validating
const isoDateString = d.toISOString()
const isoDate = new Date(isoDateString)
const dateString = isoDate.toJSON().slice(0, 17).replace('T', ' ')
// return cast value
return dateString
}
dateType (p) {
const r = this.dateTimeType(p)
if (r && typeof r === 'string') return r.slice(0,10)
else return r
}
arrayType (p) {
return Array.isArray(p.value) ? p.value : [p.value]
}
objectType (p) {
return p
}
serializeType (p) {
let r
/*
if (p.options.deserialize) {
if (typeof (p.value) !== 'string') {
throw this._typeError(p.fieldName)
}
try {
// Attempt to stringify
r = CircularJSON.parse(p.value)
// It worked: return r
return r
} catch (e) {
throw this._typeError(p.fieldName)
}
} else {
*/
try {
r = CircularJSON.stringify(p.value)
// It worked: return r
return r
} catch (e) {
throw this._typeError(p.fieldName)
}
//
/*
}
*/
}
booleanType (p) {
if (typeof (p.value) === 'string') {
if (p.value === (p.definition.stringFalseWhen || 'false')) return false
else if ((p.value === (p.definition.stringTrueWhen || 'true')) || (p.value === (p.definition.stringTrueWhen || 'on'))) return true
else return false
} else {
return !!p.value
}
}
// Cast an ID for this particular engine. If the object is in invalid format, it won't
// get cast, and as a result check will fail
idType (p) {
const n = parseInt(p.value)
if (isNaN(n)) {
throw this._typeError(p.fieldName)
} else {
return n
}
}
// Built-in parameters
minParam (p) {
if (typeof p.value === 'undefined') return
if (p.definition.type === 'number' && typeof p.value === 'number' && Number(p.value) < p.parameterValue) {
throw this._paramError(p.fieldName, "Field's value is too low")
}
if (p.definition.type === 'string' && p.value.toString && p.value.toString().length < p.parameterValue) {
throw this._paramError(p.fieldName, 'Field is too short')
}
}
maxParam (p) {
if (typeof p.value === 'undefined') return
if (p.definition.type === 'number' && typeof p.value === 'number' && Number(p.value) > p.parameterValue) {
throw this._paramError(p.fieldName, "Field's value is too high")
}
if (p.definition.type === 'string' && p.value.toString && p.value.toString().length > p.parameterValue) {
throw this._paramError(p.fieldName, 'Field is too long')
}
}
validatorParam (p) {
if (typeof (p.parameterValue) !== 'function') {
throw (new Error('Validator function needs to be a function, found: ' + typeof (p.parameterValue)))
}
const r = p.parameterValue(p.object[p.fieldName], p.object, { schema: this, fieldName: p.fieldName})
if (typeof (r) === 'string') throw this._paramError(p.fieldName, r)
}
uppercaseParam (p) {
if (p.definition.type !== 'string' || typeof p.value !== 'string') return
return p.value.toUpperCase()
}
lowercaseParam (p) {
if (p.definition.type !== 'string' || typeof p.value !== 'string') return
return p.value.toLowerCase()
}
trimParam (p) {
// For strings, trim works as intended: it will trim the cast string
if (p.definition.type === 'string' && typeof p.value === 'string') {
return p.value.substr(0, p.parameterValue)
// For non-string values, it will however check the original value. If it's longer than it should, it will puke
} else {
if (Number.isInteger(Number(p.valueBeforeCast)) && String(Number(p.valueBeforeCast)).length > p.parameterValue) throw this._paramError(p.fieldName, 'Value out of range')
}
}
lengthParam (p) {
return this.trimParam(p)
}
defaultParam (p) {
let v
if (typeof (p.valueBeforeCast) === 'undefined') {
if (typeof (p.parameterValue) === 'function') {
v = p.parameterValue(p)
} else {
v = p.parameterValue
}
return v
}
}
notEmptyParam (p) {
const bc = p.valueBeforeCast
const bcs = (typeof bc !== 'undefined' && bc !== null && bc.toString ? bc.toString() : '')
if (p.parameterValue && !Array.isArray(p.value) && typeof (bc) !== 'undefined' && bcs === '') {
throw this._paramError(p.fieldName, 'Field cannot be empty')
}
}
_typeError (field) {
const e = new Error('Error with field: ' + field)
e.errorObject = { field, message: 'Error during casting' }
return e
}
_paramError (field, message) {
const e = new Error(message)
e.errorObject = { field, message }
return e
}
// Options:
//
// * options.onlyObjectValues -- Will apply cast for existing object's keys rather than the schema itself
// * options.skipFields -- To know what casts need to be skipped
// * options.skipParams -- Won't apply specific params for specific fields
// * options.emptyAsNull -- Empty string values will be cast to null (also as a per-field option)
// * options.canBeNull -- All values can be null (also as a per-field option)
//
// * Common parameters for every type
// * required -- the field is required
// * canBeNull -- the "null" value is always accepted
// * emptyAsNull -- an empty string will be stored as null
//
// This will run _cast and _param
async validate (object, options) {
const errors = []
let skipBoth
let skipCast
let targetObject
let fieldName
let result
function emptyString (s) {
return String(s) === ''
}
// Copy object over
const validatedObject = Object.assign({}, object)
options = options || {}
// Check for spurious fields not in the schema
for (fieldName in object) {
if (typeof this.structure[fieldName] === 'undefined') {
errors.push({ field: fieldName, message: 'Field not allowed' })
}
}
// Set the targetObject. If the target is the object itself,
// then missing fields won't be a problem
if (options.onlyObjectValues) targetObject = object
else targetObject = this.structure
for (fieldName in targetObject) {
const definition = this.structure[fieldName]
if (!definition) continue
// The checking logic will check if cast -- or both cast and params --
// should be skipped
skipCast = false
skipBoth = false
let canBeNull
if (definition.default === null) canBeNull = true
else if (typeof definition.canBeNull !== 'undefined') canBeNull = definition.canBeNull
else if (typeof options.canBeNull !== 'undefined') canBeNull = !!options.canBeNull
else canBeNull = false
let emptyAsNull
if (typeof definition.emptyAsNull !== 'undefined') emptyAsNull = definition.emptyAsNull
else if (typeof options.emptyAsNull !== 'undefined') emptyAsNull= !!options.emptyAsNull
else emptyAsNull = false
// If emptyAsNull is set, then canBeNull is implicitly set
if (emptyAsNull) {
canBeNull = true
}
// Skip cast/param if so required by the skipFields array
if (Array.isArray(options.skipFields) && options.skipFields.indexOf(fieldName) !== -1) {
skipBoth = true
}
// Skip castParam if value is `undefined` AND it IS required (enriching error)
// NOTE: this won't happen if 'required' is in the list of parameters to be skipped
if (definition.required && typeof (object[fieldName]) === 'undefined') {
if (!this._paramToBeSkipped('required', options.skipParams, fieldName)) {
skipBoth = true
errors.push({ field: fieldName, message: 'Field required' })
}
}
// Skip casting if value is `undefined` AND it's not required
if (!definition.required && typeof (object[fieldName]) === 'undefined') {
skipCast = true
}
// Empty string: check if it should be forced to null
if (emptyString(object[fieldName])) {
if (emptyAsNull) {
validatedObject[fieldName] = null
skipBoth = true
}
}
// If it's null, then really check: either canBeNull is true, or return with a message
if (object[fieldName] === null) {
skipBoth = true
if (!canBeNull) {
errors.push({ field: fieldName, message: 'Field cannot be null' })
}
}
// If cast is skipped for whatever reason, params will never go through either
if (skipBoth) continue
if (!skipCast) {
// Run the xxxType function for a specific type
if (typeof (this[definition.type + 'Type']) === 'function') {
try {
result = await this[definition.type + 'Type']({
definition,
value: object[fieldName],
fieldName,
object: validatedObject,
objectBeforeCast: object,
valueBeforeCast: object[fieldName],
definitionName: definition.type,
options,
computedOptions: {
emptyAsNull,
canBeNull
}
})
} catch (e) {
if (!e.errorObject) throw e
errors.push(e.errorObject)
}
if (typeof result !== 'undefined') validatedObject[fieldName] = result
} else {
throw (new Error('No casting function found, type probably wrong: ' + definition.type))
}
}
for (const parameterName in this.structure[fieldName]) {
//
// If it's to be skipped, we shall skip -- e.g. `options.skipParams == { tabId: ['required'] }` to
// skip `required` parameter for `tabId` field
if (this._paramToBeSkipped(parameterName, options.skipParams, fieldName)) continue
if (parameterName !== 'type' && typeof (this[parameterName + 'Param']) === 'function') {
try {
result = await this[parameterName + 'Param']({
definition,
value: validatedObject[fieldName],
fieldName,
object: validatedObject,
objectBeforeCast: object,
valueBeforeCast: object[fieldName],
parameterName,
parameterValue: definition[parameterName],
options: options,
computedOptions: {
emptyAsNull,
canBeNull
}
})
} catch (e) {
if (!e.errorObject) throw e
errors.push(e.errorObject)
}
if (typeof (result) !== 'undefined') validatedObject[fieldName] = result
}
}
}
return { validatedObject, errors }
}
_paramToBeSkipped (parameterName, skipParams, fieldName) {
if (typeof (skipParams) !== 'object' || skipParams === null) return false
if (Array.isArray(skipParams[fieldName]) && skipParams.indexOf(parameterName) !== -1) return true
return false
}
cleanup (object, parameterName) {
const newObject = {}
for (const k in object) {
if (!this.structure[k]) continue
if (this.structure[k][parameterName]) {
delete object[k]
newObject[k] = object[k]
}
}
return newObject
}
}
exports = module.exports = SimpleSchema
/*
let s = new SimpleSchema({
level: { type: 'number', default: 10 },
name: { type: 'string', trim: 50 },
surname: { type: 'string', required: true, trim: 10 },
age: { type: 'number', min: 10, max: 20 }
})
let { validatedObject, errors } = s.validate({ name: 'Tony', surname: 'Mobily1234567890' }, { __onlyObjectValues: true })
console.log('RESULT:', validatedObject, errors)
*/