valueToContent method

Content valueToContent(
  1. DataSchemaValue<Object?>? value,
  2. DataSchema? dataSchema, [
  3. String mediaType = defaultMediaType
])

Converts a value to a byte representation based on its mediaType.

The passed value is validated before the conversion in accordance to the dataSchema that is being passed to the method. The value might be null, indicating that an equivalent of JavaScript's undefined is being passed to the method. In this case, validation fails if a non-empty dataSchema is present, as some kind of DataSchemaValue is expected.

If the indicated mediaType is not supported, the method will try to try to treat it as a UTF-8 string.

Implementation

Content valueToContent(
  DataSchemaValue<Object?>? value,
  DataSchema? dataSchema, [
  String mediaType = defaultMediaType,
]) {
  _validateValue(value, dataSchema);

  if (value == null) {
    return Content(mediaType, const Stream.empty());
  }

  final parsedMediaType = MediaType.parse(mediaType);
  final mimeType = parsedMediaType.mimeType;
  final parameters = parsedMediaType.parameters;

  // TODO(JKRhb): Reevaluate usage of TextCodec here
  final codec = _getCodecFromMediaType(mimeType) ?? TextCodec();

  final bytes = codec.valueToBytes(value, dataSchema, parameters);
  return Content(mediaType, Stream.value(bytes));
}