@@ -20,6 +20,27 @@ class CustomObjectsModel(BaseModel):
2020 def _generate_key (self , obj ):
2121 return obj .container , obj .key
2222
23+ def add (self , draft , id = None ):
24+ """Add a new object to the storage.
25+
26+ If the container/key already exists we update the value as long as the
27+ version matches. otherwise create a new item
28+ """
29+ new_obj = self ._create_from_draft (draft , id )
30+ current_obj = self ._get_by_container_key (new_obj .container , new_obj .key )
31+
32+ if current_obj :
33+ if current_obj ["version" ] != new_obj .version :
34+ raise ValueError (
35+ "Version mismatch: got %d, expected %d"
36+ % (new_obj .version , current_obj ["version" ])
37+ )
38+ current_obj ["value" ] = new_obj .value
39+ self .save (current_obj )
40+ return current_obj
41+ else :
42+ return self ._store_obj (new_obj )
43+
2344 def _create_from_draft (
2445 self , obj : types .CustomObjectDraft , id : typing .Optional [str ] = None
2546 ) -> types .CustomObject :
@@ -34,6 +55,18 @@ def _create_from_draft(
3455 last_modified_at = datetime .datetime .now (datetime .timezone .utc ),
3556 )
3657
58+ def _get_by_container_key (
59+ self , container : str , key : str
60+ ) -> typing .Optional [typing .Dict ]:
61+ return next (
62+ (
63+ obj
64+ for obj in self .objects .values ()
65+ if obj ["container" ] == container and obj ["key" ] == key
66+ ),
67+ None ,
68+ )
69+
3770
3871class CustomObjectsBackend (ServiceBackend ):
3972 service_path = "custom-objects"
@@ -59,14 +92,7 @@ def query_by_container(self, request, container: str):
5992 return self .query (request )
6093
6194 def get_by_container_key (self , request , container : str , key : str ):
62- item = next (
63- (
64- obj
65- for obj in self .model .objects .values ()
66- if obj ["container" ] == container and obj ["key" ] == key
67- ),
68- None ,
69- )
95+ item = self .model ._get_by_container_key (container , key )
7096 if item :
7197 return create_commercetools_response (request , json = item )
7298 else :
0 commit comments