acceptableContentTypes property Null safety

List<ContentType> acceptableContentTypes

The acceptable content types for a Response returned for this instance.

This list is determined by parsing the Accept header (or the concatenation of multiple Accept headers). The list is ordered such the more desirable content-types appear earlier in the list. Desirability is determined by a q-value (if one exists) and the specificity of the content-type.

See also acceptsContentType.

Implementation

List<ContentType> get acceptableContentTypes {
  if (_cachedAcceptableTypes == null) {
    try {
      final contentTypes = raw.headers[HttpHeaders.acceptHeader]
              ?.expand((h) => h.split(",").map((s) => s.trim()))
              .where((h) => h.isNotEmpty)
              .map(ContentType.parse)
              .toList() ??
          [];

      contentTypes.sort((c1, c2) {
        final num q1 = num.parse(c1.parameters["q"] ?? "1.0");
        final q2 = num.parse(c2.parameters["q"] ?? "1.0");

        final comparison = q1.compareTo(q2);
        if (comparison == 0) {
          if (c1.primaryType == "*" && c2.primaryType != "*") {
            return 1;
          } else if (c1.primaryType != "*" && c2.primaryType == "*") {
            return -1;
          }

          if (c1.subType == "*" && c2.subType != "*") {
            return 1;
          } else if (c1.subType != "*" && c2.subType == "*") {
            return -1;
          }
        }

        return -comparison;
      });

      _cachedAcceptableTypes = contentTypes;
    } catch (_) {
      throw Response.badRequest(
        body: {"error": "accept header is malformed"},
      );
    }
  }
  return _cachedAcceptableTypes!;
}