toDataMap method

Map<String, dynamic> toDataMap(
  1. {Map<String, PcoResource>? withRelated,
  2. List<PcoResource>? withIncluded}
)

create a json-api Map for this object automatically selecting create or update based on the existence of the id field. Will result in something like this:

{'data': {'type': 'Type', 'attributes': {...attributes}}}

if withRelated or withIncluded are specified, the returned map will include json-api compatible relationship / included fields too since some post/patch endpoints may require them

if any of the manual arguments are specified, they will override the with arguments

Implementation

Map<String, dynamic> toDataMap({
  Map<String, PcoResource>? withRelated,
  List<PcoResource>? withIncluded,
}) {
  var resource = id == null ? toCreateResource() : toUpdateResource();

  Map<String, dynamic>? related = {};
  // add the relationships if requested
  if (withRelated != null) {
    related = {
      for (var e in withRelated.entries)
        e.key: {'data': e.value.toIdResource()},
    };
  }

  if (_hasManualRelationships) {
    related = {
      ...related,
      for (var e in _relationships.entries)
        e.key: {
          'data': e.value.length == 1
              ? e.value.first.toIdResource()
              : [for (var v in e.value) v.toIdResource()]
        },
    };
  }
  if (related.isNotEmpty) resource['relationships'] = related;

  List<Map<String, dynamic>> included = [];
  if (withIncluded != null) {
    included = [
      for (var i in withIncluded) i.toJson(includeRelationships: true)
    ];
  }
  if (_hasManualIncluded) {
    included = [
      ...included,
      for (var i in _included) i.toJson(includeRelationships: true)
    ];
  }
  return {
    'data': resource,
    if (included.isNotEmpty) 'included': included,
  };
}