Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Add validation for jsonschema of dynamic params

Dylan Smithd81ec7c494f6
diff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.py
index 92d362958..c07c33d71 100644
--- a/wger/measurements/api/serializers.py
+++ b/wger/measurements/api/serializers.py
@@ -17,6 +17,7 @@
from decimal import Decimal
# Third Party
+import jsonschema
from rest_framework import serializers
# wger
@@ -35,6 +36,45 @@ class UnitSerializer(serializers.ModelSerializer):
model = Category
fields = ('id', 'name', 'unit', 'dynamic_type', 'dynamic_params')
+ def validate(self, data):
+ """
+ Validate the dynamic_params JSON matches the required schema for the selected dynamic_type.
+ """
+ # get type and params
+ dynamic_type = data.get(
+ 'dynamic_type', getattr(self.instance, 'dynamic_type', Category.DynamicType.NONE)
+ )
+ dynamic_params = data.get('dynamic_params', getattr(self.instance, 'dynamic_params', {}))
+
+ # if dynamic type is none, just clear params to avoid excessive validation
+ if dynamic_type == Category.DynamicType.NONE:
+ data['dynamic_params'] = {}
+ return super().validate(data)
+
+ # define the allowed JSON structures
+ schemas = {
+ Category.DynamicType.BMI: {
+ 'type': 'object',
+ 'additionalProperties': False,
+ },
+ # when one rep max is added it can go here
+ # Category.DynamicType.ONE_REP_MAX: {
+ # "type": "object",
+ # "properties": {"exercise_id": {"type": "integer"}, "max_reps": {"type": "integer"}},
+ # "required": ["exercise_id"],
+ # "additionalProperties": False
+ # }
+ }
+
+ schema = schemas.get(dynamic_type)
+ if schema:
+ try:
+ jsonschema.validate(instance=dynamic_params, schema=schema)
+ except jsonschema.exceptions.ValidationError as e:
+ raise serializers.ValidationError({'dynamic_params': e.message})
+
+ return super().validate(data)
+
class MeasurementSerializer(serializers.ModelSerializer):
"""
diff --git a/wger/measurements/models/category.py b/wger/measurements/models/category.py
index 5bb8f5b8f..cc6a06481 100644
--- a/wger/measurements/models/category.py
+++ b/wger/measurements/models/category.py
@@ -44,7 +44,7 @@ class Category(models.Model):
class DynamicType(models.TextChoices):
NONE = ('NONE',)
BMI = ('BMI',)
- # SQUAT_1RM = 'SQUAT_1RM', can be added in future
+ # ONE_REP_MAX = ('ONE_REP_MAX'), can be added in future
dynamic_type = models.CharField(
max_length=20, choices=DynamicType.choices, default=DynamicType.NONE, db_index=True