safe_repository.SafeRepository.model()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nop 1
1
"""SafeRepository is a subclass of BaseRepository that handles all raised errors
2
"""
3
4
from typing import Dict, Iterator, List, Type
5
6
from mongomantic.config import logger
7
from mongomantic.core.base_repository import BaseRepository
8
from mongomantic.core.errors import DoesNotExistError, InvalidQueryError, MultipleObjectsReturnedError, WriteError
9
from mongomantic.core.mongo_model import MongoDBModel
10
11
12
class SafeRepository(BaseRepository):
13
    class Meta:
14
        @property
15
        def model(self) -> Type[MongoDBModel]:
16
            """Model class that subclasses MongoDBModel"""
17
            raise NotImplementedError
18
19
        @property
20
        def collection(self) -> str:
21
            """String representing the MongoDB collection to use when storing this model"""
22
            raise NotImplementedError
23
24
    @classmethod
25
    def save(cls, model) -> Type[MongoDBModel]:
26
        try:
27
            return super().save(model)
28
        except WriteError as e:
29
            logger.error(e)
30
            return None
31
32
    @classmethod
33
    def get(cls, **kwargs) -> Type[MongoDBModel]:
34
        try:
35
            return super().get(**kwargs)
36
        except (DoesNotExistError, MultipleObjectsReturnedError) as e:
37
            logger.error(e)
38
            return None
39
40
    @classmethod
41
    def find(cls, **kwargs) -> Iterator[Type[MongoDBModel]]:
42
        try:
43
            gen = super().find(**kwargs)
44
            try:
45
                yield from gen
46
            except InvalidQueryError as e:
47
                logger.error(e)
48
                return None
49
50
        except InvalidQueryError as e:
51
            logger.error(e)
52
            return None
53
54
    @classmethod
55
    def aggregate(cls, pipeline: List[Dict]):
56
        try:
57
            gen = super().aggregate(pipeline)
58
            try:
59
                yield from gen
60
            except InvalidQueryError as e:
61
                logger.error(e)
62
                return None
63
64
        except InvalidQueryError as e:
65
            logger.error(e)
66
            return None
67