mirror of
https://github.com/GSA/notifications-api.git
synced 2025-12-16 02:02:13 -05:00
This is the schema that individual notifications will conform to when they are returned from this API. JSON logic enforces that the right keys are set depending on the `"type"`. (eg a schema with `"type": "sms"` must have a `"phone_number"` value and it cannot have an `"email_address"`)
48 lines
1.6 KiB
Python
48 lines
1.6 KiB
Python
import json
|
|
|
|
from jsonschema import (Draft4Validator, ValidationError, FormatChecker)
|
|
from notifications_utils.recipients import (validate_phone_number, validate_email_address, InvalidPhoneError,
|
|
InvalidEmailError)
|
|
|
|
|
|
def validate(json_to_validate, schema):
|
|
format_checker = FormatChecker()
|
|
|
|
@format_checker.checks('phone_number', raises=InvalidPhoneError)
|
|
def validate_schema_phone_number(instance):
|
|
if instance is not None:
|
|
validate_phone_number(instance)
|
|
return True
|
|
|
|
@format_checker.checks('email_address', raises=InvalidEmailError)
|
|
def validate_schema_email_address(instance):
|
|
if instance is not None:
|
|
validate_email_address(instance)
|
|
return True
|
|
|
|
validator = Draft4Validator(schema, format_checker=format_checker)
|
|
errors = list(validator.iter_errors(json_to_validate))
|
|
if errors.__len__() > 0:
|
|
raise ValidationError(build_error_message(errors))
|
|
return json_to_validate
|
|
|
|
|
|
def build_error_message(errors):
|
|
fields = []
|
|
for e in errors:
|
|
field = "{} {}".format(e.path[0], e.schema.get('validationMessage')) if e.schema.get(
|
|
'validationMessage') else __format_message(e)
|
|
fields.append({"error": "ValidationError", "message": field})
|
|
message = {
|
|
"status_code": 400,
|
|
"errors": fields
|
|
}
|
|
|
|
return json.dumps(message)
|
|
|
|
|
|
def __format_message(e):
|
|
s = e.message.split("'")
|
|
msg = "{}{}".format(s[1], s[2])
|
|
return msg if not e.cause else "{} {}".format(e.path[0], e.cause.message)
|