deserialize method
Returns a DeserializedData object when deserializing a given data
.
key
can be used to supply a specific key
when deserializing ONE model.
Implementation
@override
DeserializedData<T, DataModel> deserialize(Object? data, {String? key}) {
final result = DeserializedData<T, DataModel>([], included: []);
dynamic addIncluded(id, RemoteAdapter? adapter) {
if (id is Map && adapter != null) {
final data = adapter.deserialize(id as Map<String, dynamic>);
result.included
..add(data.model as DataModel<DataModel>)
..addAll(data.included);
return data.model!.id;
}
return id;
}
if (data == null || data == '') {
return result;
}
if (data is Map) {
data = [data];
}
if (data is Iterable) {
for (final mapIn in data) {
final mapOut = <String, dynamic>{};
final relationships = localAdapter.relationshipsFor();
for (final mapInKey in mapIn.keys) {
final mapOutKey = fieldForKey(mapInKey.toString());
final metadata = relationships[mapOutKey];
if (metadata != null) {
final _type = metadata['type'] as String;
if (metadata['kind'] == 'BelongsTo') {
final id = addIncluded(mapIn[mapInKey], adapters[_type]);
mapOut[mapOutKey] = id == null
? null
: graph.getKeyForId(_type, id,
keyIfAbsent: DataHelpers.generateKey(_type));
}
if (metadata['kind'] == 'HasMany') {
mapOut[mapOutKey] = (mapIn[mapInKey] as Iterable)
.map((id) {
id = addIncluded(id, adapters[_type]);
return id == null
? null
: graph.getKeyForId(_type, id,
keyIfAbsent: DataHelpers.generateKey(_type));
})
.filterNulls
.toImmutableList();
}
} else {
// regular field mapping
mapOut[mapOutKey] = mapIn[mapInKey];
}
}
final model = localAdapter.deserialize(mapOut);
model._initialize(adapters, key: key, save: true);
result.models.add(model);
}
}
return result;
}