-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconverter.js
47 lines (43 loc) · 1.37 KB
/
converter.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
const Conversion = require('./conversion')
const { toCamelObject } = require('./formatters/string-cases')
const { ValidationError, ForbiddenError, EmptyResultError } = require('./errors')
class Converter {
constructor (validatedObject, transformedObject, options = {}) {
if (validatedObject instanceof Converter) {
validatedObject = validatedObject.validatedObject
}
this.validatedObject = validatedObject
this.currentValue = null
this.currentProperty = null
this.transformedObject = transformedObject || {}
this.conversions = []
this.options = {
camelize: false,
...options
}
};
convert (property) {
const conversion = new Conversion(this.validatedObject, property, this.transformedObject)
this.conversions.push(conversion)
return conversion
}
validate () {
return Promise.resolve()
.then(() => {
const exceptions = []
for (var conversion of this.conversions) {
try {
conversion.execute()
} catch (e) {
exceptions.push(e.message)
}
}
if (exceptions.length === 0) {
return this.options.camelize ? toCamelObject(this.transformedObject, 1) : this.transformedObject
} else {
throw new ValidationError(`Validation errors: ${exceptions.join('; ')}.`)
}
})
}
}
module.exports = Converter