-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
55 lines (50 loc) · 1.88 KB
/
index.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
48
49
50
51
52
53
54
55
const joi = require('joi')
/**
* Helper function to validate an object against the provided schema,
* and to throw a custom error if object is not valid.
*
* @param {Object} object The object to be validated.
* @param {String} label The label to use in the error message.
* @param {JoiSchema} schema The Joi schema to validate the object against.
*/
function validateObject (object = {}, label, schema, options) {
// Skip validation if no schema is provided
if (schema) {
// Validate the object against the provided schema
const { error, value } = joi.validate(object, schema, options)
if (error) {
// Throw error with custom message if validation failed
throw new Error(`Invalid ${label} - ${error.message}`)
}
}
}
/**
* Generate a Koa middleware function to validate a request using
* the provided validation objects.
*
* @param {Object} validationObj
* @param {Object} validationObj.headers The request headers schema
* @param {Object} validationObj.params The request params schema
* @param {Object} validationObj.query The request query schema
* @param {Object} validationObj.body The request body schema
* @returns A validation middleware function.
*/
function validate (validationObj) {
// Return a Koa middleware function
return (ctx, next) => {
try {
// Validate each request data object in the Koa context object
validateObject(ctx.headers, 'Headers', validationObj.headers, { allowUnknown: true })
validateObject(ctx.params, 'URL Parameters', validationObj.params)
validateObject(ctx.query, 'URL Query', validationObj.query)
if (ctx.request.body) {
validateObject(ctx.request.body, 'Request Body', validationObj.body)
}
return next()
} catch (err) {
// If any of the objects fails validation, send an HTTP 400 response.
ctx.throw(400, err.message)
}
}
}
module.exports = validate