-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmango-validator.mixin.ts
183 lines (162 loc) · 5.08 KB
/
mango-validator.mixin.ts
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
import { TVO_DEFAULTS } from '@/constants'
import type { IMangoValidator, MangoValidatorOptions } from '@/interfaces'
import { ExceptionStatusCode } from '@flex-development/exceptions/enums'
import Exception from '@flex-development/exceptions/exceptions/base.exception'
import type { ObjectPlain, ObjectUnknown } from '@flex-development/tutils'
import type { ClassTransformOptions as TransformOpts } from 'class-transformer'
import { classToPlain } from 'class-transformer'
import type { ClassType } from 'class-transformer-validator'
import {
transformAndValidate as tv,
transformAndValidateSync as tvSync
} from 'class-transformer-validator'
import type { ValidationError, ValidatorOptions } from 'class-validator'
import merge from 'lodash.merge'
/**
* @file Mixin - MangoValidator
* @module mixins/MangoValidator
*/
/**
* Handles validating repository entities.
*
* @template E - Entity
*
* @class
* @implements {IMangoValidator<E>}
*/
export default class MangoValidator<E extends ObjectPlain = ObjectUnknown>
implements IMangoValidator<E> {
/**
* @readonly
* @instance
* @property {boolean} enabled - Toggle validation
*/
readonly enabled: boolean
/**
* @readonly
* @instance
* @property {ClassType<E>} model - Entity model
*/
readonly model: ClassType<E>
/**
* @readonly
* @instance
* @property {string} model_name - Name of entity model
*/
readonly model_name: string
/**
* @readonly
* @instance
* @property {Omit<MangoValidatorOptions, 'enabled'>} tvo - Validation options
*/
readonly tvo: Omit<MangoValidatorOptions, 'enabled'>
/**
* @readonly
* @instance
* @property {typeof tv} validator - Async validation function
*/
readonly validator: typeof tv = tv
/**
* @readonly
* @instance
* @property {typeof tvSync} validatorSync - Synchronous validation function
*/
readonly validatorSync: typeof tvSync = tvSync
/**
* Creates a new repository validator.
*
* See:
*
* - https://github.com/pleerock/class-validator
* - https://github.com/typestack/class-transformer
* - https://github.com/MichalLytek/class-transformer-validator
*
* @param {ClassType<E>} model - Entity model
* @param {MangoValidatorOptions} [options] - Mango Validation API options
* @param {boolean} [options.enabled] - Toggle schema validation
* @param {TransformOpts} [options.transformer] - `class-transformer` options
* @param {ValidatorOptions} [options.validator] - `class-validator` options
*/
constructor(model: ClassType<E>, options: MangoValidatorOptions = {}) {
const { enabled = true, transformer = {}, validator = {} } = options
this.enabled = enabled
this.model = model
this.model_name = new this.model().constructor.name
this.tvo = merge(TVO_DEFAULTS, { transformer, validator })
}
/**
* Validates {@param value} against {@see MangoValidator#model} if the Mango
* Validation API is enabled. Otherwise, the original value will be returned.
*
* References:
*
* - https://github.com/MichalLytek/class-transformer-validator
*
* @template Value - Type of value being validated
*
* @param {Value} value - Data to validate
* @return {Promise<E | Value>} - Promise containing entity or original value
* @throws {Exception}
*/
async check<Value extends unknown = ObjectPlain>(
value: Value = {} as Value
): Promise<E | Value> {
if (!this.enabled) return value
let data = {} as E
try {
data = (await this.validator<E>(this.model, value as any, this.tvo)) as E
} catch (error) {
throw this.handleError(error)
}
return classToPlain<E>(data) as E
}
/**
* Synchronous version of {@see MangoValidator#check}.
*
* @template Value - Type of value being validated
*
* @param {Value} value - Data to validate
* @return {E | Value} - Entity or original value
* @throws {Exception}
*/
checkSync<Value extends unknown = ObjectPlain>(
value: Value = {} as Value
): E | Value {
if (!this.enabled) return value
let data = {} as E
try {
data = this.validatorSync<E>(this.model, value as any, this.tvo) as E
} catch (error) {
throw this.handleError(error)
}
return classToPlain<E>(data) as E
}
/**
* Converts an error into an `Exception`.
*
* @param {Error | ValidationError[]} error - Error to convert
* @return {Exception} New exception
*/
handleError(error: Error | ValidationError[]): Exception {
let code = ExceptionStatusCode.INTERNAL_SERVER_ERROR
let data = { model_name: this.model_name }
let message = ''
let stack: string | undefined = undefined
if (Array.isArray(error)) {
const errors = error as ValidationError[]
const properties = errors.map(e => e.property)
code = ExceptionStatusCode.BAD_REQUEST
data = merge(data, { errors })
message = `${this.model_name} entity validation failure: [${properties}]`
} else {
message = error.message
stack = error.stack
}
return new Exception(
code,
message,
merge(data, { options: this.tvo }),
stack
)
}
}