documentToJson method

JsonObject documentToJson(
  1. Document document
)

Converts a Firestore Document to a JSON object.

This function extracts the fields from the Firestore document, converts them to JSON objects using the valueUtils, and adds metadata fields.

Implementation

JsonObject documentToJson(Document document) {
  final docJson = <String, dynamic>{};

  final entries = document.fields?.entries ?? [];

  for (final entry in entries) {
    docJson[entry.key] = valueUtils.toJsonObject(entry.value);
  }

  docJson[metaName] = document.id(pathUtils);

  if (document.createTime != null) {
    final createTime =
        DateTime.tryParse(document.createTime!)?.toUtc().toIso8601String();
    docJson[metaCreateTime] = createTime;
  }

  if (document.updateTime != null) {
    final updateTime =
        DateTime.tryParse(document.updateTime!)?.toUtc().toIso8601String();
    docJson[metaUpdateTime] = updateTime;
  }

  return docJson;
}