-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathvalidation.ts
More file actions
39 lines (34 loc) · 1.06 KB
/
validation.ts
File metadata and controls
39 lines (34 loc) · 1.06 KB
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
import { Request, Response, NextFunction } from 'express'
import omit from 'lodash/omit.js'
import Joi from 'joi'
export const validate = (
schema: Joi.Schema,
options: {
omit?: string[]
} = {}
) => {
const { omit: omitProps } = options
return (req: Request, res: Response, next: NextFunction) => {
let data = req.body
if (omitProps) {
data = omit(data, omitProps as any)
}
const { value, error } = schema.validate(data, {
abortEarly: true,
convert: true,
// The website API pages send extra UI-only keys; accept and strip anything unknown.
allowUnknown: true,
stripUnknown: { objects: true },
})
if (error) {
return res.status(400).json({
errors: error.details.map(({ message, path }) => {
return `${message}${path ? ` (${path})` : ''}`
}),
})
}
// @ts-expect-error no type for req.payload
req.payload = value
next()
}
}