-
Notifications
You must be signed in to change notification settings - Fork 9
/
validate.ts
33 lines (25 loc) · 949 Bytes
/
validate.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
import { Error } from 'common-errors'
import { Microfleet } from '@microfleet/core'
import { HttpStatusError } from '@microfleet/validation'
import { RequestDataKey } from '../../router'
import { ServiceRequest } from '../../types/router'
async function validateHandler(this: Microfleet, request: ServiceRequest): Promise<void> {
const { validator } = this
const { schema } = request.action
// disable validation
if (schema === null || schema === false) {
return
}
const paramsKey = RequestDataKey[request.method] ?? 'params'
try {
// @todo (important) handle schema not found error and log it
const validationResult = await validator.validate(schema as string, request[paramsKey])
request[paramsKey] = validationResult
} catch (error: any) {
if (error.constructor === HttpStatusError) {
throw error
}
throw new Error('internal validation error', error)
}
}
export default validateHandler