-
Notifications
You must be signed in to change notification settings - Fork 3
Mappers
Dustin Catap edited this page Nov 12, 2023
·
1 revision
Mappers are domain classes that convert objects from one type to another. They are useful when we want to convert data from one layer to another.
abstract interface class ObjectMapper {
T mapObject<S, T>(S? object);
Iterable<T> mapObjects<S, T>(Iterable<S> objects);
}
-
mapObject
converts a single object from one type to another. -
mapObjects
converts a list of objects from one type to another.
We use auto_mappr
to generate mappers. This package uses build_runner
to generate mappers.
Below is an example of a mapper class:
abstract interface class PostMapper implements ObjectMapper {}
@AutoMappr(<MapType<Object, Object>>[
MapType<PostDataContract, PostEntity>(),
MapType<PostDataContract, PostDataObject>(fields: <Field>[
Field.from('postId', from: 'id'),
]),
MapType<PostDataObject, PostEntity>(fields: <Field>[
Field.from('id', from: 'postId'),
]),
])
@LazySingleton(as: PostMapper)
class PostMapperImpl extends $PostMapperImpl implements PostMapper {
@override
T mapObject<S, T>(S? object) => convert(object);
@override
Iterable<T> mapObjects<S, T>(Iterable<S> objects) => convertIterable(objects);
}
-
@AutoMappr
is used to annotate the class as a mapper. TheMapType
parameter is used to specify the mapping between two types. Thefields
parameter is used to specify the mapping between two fields. Thefrom
parameter is used to specify the name of the field to map from. Theto
parameter is used to specify the name of the field to map to. If theto
parameter is not specified, the name of the field to map to will be the same as the name of the field to map from. - We implicitly added a field mapping from
PostDataContract.id
toPostDataObject.postId
and vice versa. This is because theid
field ofPostDataContract
is mapped to thepostId
field ofPostDataObject
by default. - After implementing
ObjectMapper
, we point the implemented methods to the generated methods from$PostMapperImpl
.
💡 TIP
- Use the code snippet shortcut
mapper
to create a mapper class.