(schema, payload /*, description*/)
| 15 | * @returns {Promise} |
| 16 | */ |
| 17 | const apiValidator = async (schema, payload /*, description*/) => { |
| 18 | if (!schema) { |
| 19 | throw new errs.ValidationError("Schema is undefined"); |
| 20 | } |
| 21 | |
| 22 | // Can't use falsy check here as valid payload could be `0` or `false` |
| 23 | if (typeof payload === "undefined") { |
| 24 | throw new errs.ValidationError("Payload is undefined"); |
| 25 | } |
| 26 | |
| 27 | |
| 28 | const validate = ajv.compile(schema); |
| 29 | |
| 30 | const valid = validate(payload); |
| 31 | |
| 32 | |
| 33 | if (valid && !validate.errors) { |
| 34 | return payload; |
| 35 | } |
| 36 | |
| 37 | |
| 38 | |
| 39 | const message = ajv.errorsText(validate.errors); |
| 40 | const err = new errs.ValidationError(message); |
| 41 | err.debug = {validationErrors: validate.errors, payload}; |
| 42 | throw err; |
| 43 | }; |
| 44 | |
| 45 | export default apiValidator; |
no test coverage detected