-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.ts
59 lines (46 loc) · 1.28 KB
/
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
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
import { Handler } from 'express';
import { SchemaMap } from '@hapi/joi'
const Joi = require('@hapi/joi');
type SuppertedKeys = 'params' | 'body' | 'query'
interface Options {
params?: SchemaMap
body?: SchemaMap
query?: SchemaMap
}
interface ExpressJoiValidate {
(schemaOptions: Options): Handler
}
/**
* Route validation using Joi
* Takes a schema with properties defined using Joi:
* - params
* - body
* - query
* Validates the request properties specified in the schema
* @param {Object} schema { params, body, query }
*/
const validate: ExpressJoiValidate = (schema) => (req, res, next) => {
if (!schema) {
return next();
}
const obj: Options = {};
['params', 'body', 'query']
.forEach((key) => {
const k: SuppertedKeys = key as SuppertedKeys
if (schema[k]) {
obj[k] = req[k];
}
});
const joiSchema = Joi.object(schema);
const { error } = joiSchema.validate(obj);
if (error) {
const field = error.details[0].path.join('.');
const message = error.details[0].message.replace(/"/g, "'");
return res.status(400).json({ message, field }).end();
}
return next();
}
// lolz required...
// https://stackoverflow.com/questions/12696236/module-exports-in-typescript
module.exports = validate;
export default validate