@@ -198,6 +198,85 @@ assert ress == {"8": {"a": 8}, "9": {"a": 9}} # True
198198```
199199
200200
201+ Object Mapper
202+ ========================================================================================
203+
204+ DictDataBase provides object mappers to model your data as classes and benefit from
205+ type hints and type checking.
206+
207+
208+ Mapping key-value items in one File
209+ ----------------------------------------------------------------------------------------
210+
211+ In this example, we will have a file called ` users.json ` , inside your storage directory
212+ (` DDB.config.storage_directory ` ) which contains the following data:
213+ ``` json
214+ {
215+ "u1" : {
216+ "first_name" : " John" ,
217+ "last_name" : " Doe" ,
218+ "age" : 21
219+ },
220+ "u2" : {
221+ "first_name" : " Jane" ,
222+ "last_name" : " Smith" ,
223+ "age" : 30 ,
224+ "phone" : " 0123456"
225+ },
226+ }
227+ ```
228+
229+ We will now map the data to classes:
230+
231+ ``` python
232+ from dictdatabase.object_mapper import FileDictModel, FileDictItemModel
233+
234+ class User (FileDictItemModel ):
235+ first_name: str
236+ last_name: str
237+ age: int
238+ phone: str | None
239+
240+ def full_name (self ):
241+ return f " { self .first_name} { self .last_name} "
242+
243+
244+ class Users (FileDictModel[User]):
245+ __file__ = " users"
246+ ```
247+
248+ A few important things are happening here:
249+ - ` FileDictItemModel ` models a key-value item inside the file.
250+ - The attributes ` first_name ` and ` last_name ` and ` age ` of ` User ` are required. If they miss in the file, a ` KeyError ` is raised.
251+ - The attribute ` phone ` is optional, and will be ` None ` if it does not exist in the file.
252+ - When defining ` Users ` , the ` FileDictModel ` must specify it's item model type as a type argument (` FileDictModel[User] ` )
253+ - ` Users ` only has to specify the file it refers to by passing the file name without the ending (` __file__ = "users" ` )
254+
255+
256+ Now, the models can be used:
257+
258+ ``` python
259+ # Get user by id
260+ u1: User = Users.get_at_key(" u1" )
261+ print (u1.full_name())
262+ >> > " John Doe"
263+
264+ # Iterate all users:
265+ for uid, user in Users.items():
266+ print (user.last_name, user.age, user.phone)
267+ >> > " Doe" , 21 , None
268+ >> > " Smith" , 30 , " 0123456"
269+
270+ # Filter
271+ u_over_25: dict[str , User] = Users.get_where(lambda uid , user : user.age > 25 )
272+ ```
273+
274+
275+
276+
277+
278+
279+
201280
202281Performance
203282========================================================================================
0 commit comments