File tree 2 files changed +43
-0
lines changed 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -57,6 +57,34 @@ def __init__(self, api_call: ApiCall):
57
57
self .api_call = api_call
58
58
self .collections : typing .Dict [str , Collection [TDoc ]] = {}
59
59
60
+ def __contains__ (self , collection_name : str ) -> bool :
61
+ """
62
+ Check if a collection exists in Typesense.
63
+
64
+ This method tries to retrieve the specified collection to check for its existence,
65
+ utilizing the Collection.retrieve() method but without caching non-existent collections.
66
+
67
+ Args:
68
+ collection_name (str): The name of the collection to check.
69
+
70
+ Returns:
71
+ bool: True if the collection exists, False otherwise.
72
+ """
73
+ if collection_name in self .collections :
74
+ try : # noqa: WPS229, WPS529
75
+
76
+ self .collections [collection_name ].retrieve () # noqa: WPS529
77
+ return True
78
+ except Exception :
79
+ self .collections .pop (collection_name , None )
80
+ return False
81
+
82
+ try : # noqa: WPS229, WPS529
83
+ Collection (self .api_call , collection_name ).retrieve ()
84
+ return True
85
+ except Exception :
86
+ return False
87
+
60
88
def __getitem__ (self , collection_name : str ) -> Collection [TDoc ]:
61
89
"""
62
90
Get or create a Collection instance for a given collection name.
Original file line number Diff line number Diff line change @@ -293,3 +293,18 @@ def test_actual_retrieve(
293
293
294
294
response [0 ].pop ("created_at" )
295
295
assert response == expected
296
+
297
+
298
+ def test_actual_contains (
299
+ actual_collections : Collections ,
300
+ delete_all : None ,
301
+ create_collection : None ,
302
+ ) -> None :
303
+ """Test that the Collections object can check if a collection exists in Typesense."""
304
+ # Test for existing collection
305
+ assert "companies" in actual_collections
306
+
307
+ # Test for non-existing collection
308
+ assert "non_existent_collection" not in actual_collections
309
+ # Test again
310
+ assert "non_existent_collection" not in actual_collections
You can’t perform that action at this time.
0 commit comments