field_types.py 1.28 KB
Newer Older
Dylan Jones's avatar
Dylan Jones committed
1
2
import enum

Dylan Jones's avatar
Dylan Jones committed
3

Dylan Jones's avatar
Dylan Jones committed
4
class FieldType(enum.Enum):
Dylan Jones's avatar
Dylan Jones committed
5
6
7
8
9
10
11
    STRING = {'value': str}
    FLOAT = {'value': float}
    INTEGER = {'value': int}
    BOOLEAN = {'value': bool}
    RATING = {'num_reviews': int, 'average_rating': float}

    def validate(self, data):
12
13
14
15
16
17
18
19
20
21
22
23
24
        """
        Given an instance of a value, verfiy that the instance satisfies the
        schema for this primitive type.  e.g. if FieldType.STRING.validate was
        called, it would make sure that the `data` parameter looked like
        {
            "value": "some string"
        }

        This method throws a ValueError if the passed value doesn't conform to the
        schema.
        :param data: the instance of this primitive to validate.
        :raises ValueError: if the passed data is incorrect
        """
Dylan Jones's avatar
Dylan Jones committed
25
26
27
28
29
        if type(data) is not dict:
            raise ValueError("YA DONE GOOFED. NEED A DICT.")
        for field in self.value:
            if field not in data:
                raise ValueError(f"Fields of type {self.name} need a {field} field")
30
31
            if type(data[field]) is not self.value[field]:
                raise ValueError(f"Expecting field of type {self.value[field]}, got {type(data[field])}")
32
33
        if len(data) != len(self.value):
            raise ValueError(f"Too many fields for field of type {self.name}")