-
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);
}-
mapObjectconverts a single object from one type to another. -
mapObjectsconverts 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);
}-
@AutoMappris used to annotate the class as a mapper. TheMapTypeparameter is used to specify the mapping between two types. Thefieldsparameter is used to specify the mapping between two fields. Thefromparameter is used to specify the name of the field to map from. Thetoparameter is used to specify the name of the field to map to. If thetoparameter 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.idtoPostDataObject.postIdand vice versa. This is because theidfield ofPostDataContractis mapped to thepostIdfield ofPostDataObjectby default. - After implementing
ObjectMapper, we point the implemented methods to the generated methods from$PostMapperImpl.
💡 TIP
- Use the code snippet shortcut
mapperto create a mapper class.