encode method

  1. @override
Future<Map<String, dynamic>> encode(
  1. dynamic content
)
override

Implementation

@override
Future<Map<String, dynamic>> encode(dynamic content) async {
  if (content is! Reply) {
    throw const FormatException('Content must be Reply');
  }

  // Get the codec for the nested content
  final codec = codecRegistry.getCodec(
    content.contentType.authorityId,
    content.contentType.typeId,
  );

  if (codec == null) {
    throw Exception('No codec found for content type: ${content.contentType.authorityId}/${content.contentType.typeId}');
  }

  // Encode the nested content
  final encodedContent = await codec.encode(content.content);

  // Build the nested EncodedContent protobuf
  final nestedEncodedContent = EncodedContent()
    ..type = (ContentTypeId()
      ..authorityId = content.contentType.authorityId
      ..typeId = content.contentType.typeId
      ..versionMajor = content.contentType.versionMajor
      ..versionMinor = 0)
    ..content = encodedContent['content'] as Uint8List;

  // Add parameters from the nested codec
  final nestedParameters = encodedContent['parameters'] as Map<String, dynamic>?;
  if (nestedParameters != null) {
    nestedParameters.forEach((key, value) {
      nestedEncodedContent.parameters[key] = value.toString();
    });
  }

  // Serialize the nested EncodedContent to bytes
  final nestedBytes = nestedEncodedContent.writeToBuffer();

  return {
    'content': Uint8List.fromList(nestedBytes),
    'parameters': {
      'reference': content.reference,
      // Store contentType for backward compatibility <- this is the reply type (Text, attachmente,etc.)
      'contentType': '${content.contentType.authorityId}/${content.contentType.typeId}',
    },
    'type': {
      'authorityId': authorityId,
      'typeId': typeId,
      'versionMajor': versionMajor,
      'versionMinor': versionMinor,
    }
  };
}