handleRelationships method

Map<String, List<PcoResource>> handleRelationships(
  1. Map<String, dynamic> items, [
  2. List<Map<String, dynamic>> included = const []
])

Implementation

Map<String, List<PcoResource>> handleRelationships(
  Map<String, dynamic> items, [
  List<Map<String, dynamic>> included = const [],
]) {
  _included.clear();

  // parse the included objects into resources
  var parsedIncludes = <String, PcoResource>{};
  for (var data in included) {
    var res = handleItem(data);
    if (res != null) parsedIncludes[res.slug] = res;
  }

  // prepare the object we will return
  var retval = <String, List<PcoResource>>{};

  // parse the relationships
  for (var key in items.keys) {
    retval[key] = <PcoResource>[];
    var value = items[key];
    var data = value['data'];
    if (data == null) continue; // no data, leave empty
    List wrapped = (data is List) ? data : [data];
    if (wrapped.isEmpty) continue;
    for (var data in wrapped) {
      var res = handleItem(data);
      if (res == null) continue;
      if (parsedIncludes.containsKey(res.slug)) {
        res = parsedIncludes[res.slug]!;

        // this resource matched a relationship, add it to the includes
        _included.add(res);
      }
      retval[key]?.add(res);
    }
  }

  return retval;
}