Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor request body validation using decorator #5920

Merged
merged 2 commits into from
Jun 21, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions backend/models/dtos/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from functools import wraps
from flask import request
from schematics.exceptions import DataError


from backend.exceptions import BadRequest


def get_validation_errors(e):
"""Returns a list of validation errors from a schematics DataError"""
return [
{"field": field, "message": str(error[0])} for field, error in e.errors.items()
]


def validate_request_body(dto_class):
"""Decorator to validate request body against a DTO class"""

def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
try:
dto = dto_class(request.get_json())
dto.validate()
request.validated_dto = dto
except DataError as e:
field_errors = get_validation_errors(e)
raise BadRequest(field_errors=field_errors)
return f(*args, **kwargs)

return wrapper

return decorator