boundedPrettyFormatBody function

String boundedPrettyFormatBody(
  1. Object? data, {
  2. int budget = 2000,
  3. int maxListItems = 50,
  4. int maxStringLength = 2000,
  5. int maxDecodeLength = 50000,
})

Like prettyFormatBody, but caps how much it walks and prints, for callers that format right away, like a logger.

Example:

final text = boundedPrettyFormatBody(response.data);
boundedPrettyFormatBody(users, maxListItems: 10); // 100 users print as 10, then '… 90 more items'

Implementation

String boundedPrettyFormatBody(
  Object? data, {
  int budget = 2000,
  int maxListItems = 50,
  int maxStringLength = 2000,
  int maxDecodeLength = 50000,
}) {
  if (data == null) return 'null';
  if (data is Uint8List) return _formatBytes(data);
  if (data is FormData) return _formatFormData(data);
  // Decoding is all-or-nothing, so a huge string is cut down as text instead of decoded in full.
  if (data is String && data.length > maxDecodeLength) {
    final cut = maxStringLength < data.length ? maxStringLength : data.length;
    return '${data.substring(0, cut)}… [${data.length} chars total]';
  }
  Object? value;
  try {
    value = data is String ? jsonDecode(data) : data;
  } catch (_) {
    return data.toString();
  }
  final remaining = [budget];
  final bounded = _boundForLogging(
    value,
    remaining,
    maxListItems: maxListItems,
    maxStringLength: maxStringLength,
  );
  try {
    return const JsonEncoder.withIndent('  ').convert(bounded);
  } catch (_) {
    return bounded.toString();
  }
}