serialize method

  1. @override
Future<Map<String, dynamic>> serialize(
  1. T model, {
  2. bool withRelationships = true,
})

Transforms native format into JSON:API

Implementation

@override
Future<Map<String, dynamic>> serialize(T model,
    {bool withRelationships = true}) async {
  var map =
      await super.serialize(model, withRelationships: withRelationships);
  map = map.filterNulls;

  // relationships
  final relationships = <String, Relationship>{};

  for (final relEntry in localAdapter.relationshipMetas.entries) {
    final key = relEntry.key;
    final type = _typeFor(relEntry.value.type);

    if (map[key] is Iterable) {
      final identifiers = (map[key] as Iterable<Object>).map((id) {
        return Identifier(type, id.toString());
      }).toList();
      relationships[key] = ToMany(identifiers);
    } else if (map[key] != null) {
      relationships[key] = ToOne(Identifier(type, map[key].toString()));
    }
    map.remove(key);
  }

  // id
  final id = map.remove('id');

  // attributes
  final attributes = Map.fromEntries(
    map.entries.map((e) => MapEntry(e.key, e.value)),
  );

  // assemble type, id, attributes, relationships in `Resource`
  final resource = NewResource(_typeFor(internalType), id?.toString());
  resource.attributes.addAll(attributes);
  resource.relationships.addAll(relationships);

  // add resource to a document
  final outbound = OutboundDataDocument.newResource(resource).toJson();

  // run decode/encode because `json_api`'s `toJson()`
  // DOES NOT return nested Map<String, dynamic>s as expected
  return json.decode(json.encode(outbound)) as Map<String, dynamic>;
}