@dvsa/appdev-api-common 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Decorator tp validate an express request body against a specified schema
|
|
3
|
-
* @param {object} schema
|
|
3
|
+
* @param {object} schema - the json schema you wish to use as the validator
|
|
4
|
+
* @param isArray - whether the body is expected to be an array
|
|
4
5
|
* @param errorDetails - whether to return detailed error messages (Note: errors are logged regardless of this setting)
|
|
5
6
|
*/
|
|
6
|
-
export declare function ValidateRequestBody<T>(schema: object, { errorDetails }?: {
|
|
7
|
+
export declare function ValidateRequestBody<T>(schema: object, { isArray, errorDetails }?: {
|
|
8
|
+
isArray: boolean;
|
|
7
9
|
errorDetails: boolean;
|
|
8
10
|
}): (_target: T, _propertyKey: string, descriptor: PropertyDescriptor) => void;
|
|
@@ -10,10 +10,11 @@ const ajv = new ajv_1.default({ removeAdditional: true, allErrors: true });
|
|
|
10
10
|
ajv.addKeyword("tsEnumNames");
|
|
11
11
|
/**
|
|
12
12
|
* Decorator tp validate an express request body against a specified schema
|
|
13
|
-
* @param {object} schema
|
|
13
|
+
* @param {object} schema - the json schema you wish to use as the validator
|
|
14
|
+
* @param isArray - whether the body is expected to be an array
|
|
14
15
|
* @param errorDetails - whether to return detailed error messages (Note: errors are logged regardless of this setting)
|
|
15
16
|
*/
|
|
16
|
-
function ValidateRequestBody(schema, { errorDetails } = { errorDetails: false }) {
|
|
17
|
+
function ValidateRequestBody(schema, { isArray, errorDetails } = { isArray: false, errorDetails: false }) {
|
|
17
18
|
return (_target, _propertyKey, descriptor) => {
|
|
18
19
|
const originalMethod = descriptor.value;
|
|
19
20
|
descriptor.value = async function (body, res, next) {
|
|
@@ -26,7 +27,11 @@ function ValidateRequestBody(schema, { errorDetails } = { errorDetails: false })
|
|
|
26
27
|
const payload = Buffer.isBuffer(body)
|
|
27
28
|
? JSON.parse(body.toString("utf-8"))
|
|
28
29
|
: body;
|
|
29
|
-
|
|
30
|
+
// Create the appropriate schema based on whether we're validating an array
|
|
31
|
+
const schemaToValidate = isArray
|
|
32
|
+
? { type: "array", items: schema }
|
|
33
|
+
: schema;
|
|
34
|
+
const validateFunction = ajv.compile(schemaToValidate);
|
|
30
35
|
// validate the request body against the schema passed in
|
|
31
36
|
const isValid = validateFunction(payload);
|
|
32
37
|
// if an error exists, then return a 400 with details
|