fromResponse static method

Future<CacheResponse> fromResponse({
  1. required String key,
  2. required CacheOptions options,
  3. required Response response,
})

Implementation

static Future<CacheResponse> fromResponse({
  required String key,
  required CacheOptions options,
  required Response response,
}) async {
  final dateStr = response.headers[dateHeader]?.join(',');
  DateTime? date;
  if (dateStr != null) {
    try {
      date = HttpDate.parse(dateStr);
    } catch (_) {
      // Invalid date format => ignored
    }
  }

  final expiresDateStr = response.headers[expiresHeader]?.join(',');
  DateTime? httpExpiresDate;
  if (expiresDateStr != null) {
    try {
      httpExpiresDate = HttpDate.parse(expiresDateStr);
    } catch (_) {
      // Invalid date format => meaning something already expired
      httpExpiresDate = DateTime.fromMicrosecondsSinceEpoch(0, isUtc: true);
    }
  }

  final checkedMaxStale = options.maxStale;

  return CacheResponse(
    cacheControl: CacheControl.fromHeader(
      response.headers[cacheControlHeader],
    ),
    content: null,
    date: date,
    eTag: response.headers[etagHeader]?.join(','),
    expires: httpExpiresDate,
    headers: utf8.encode(jsonEncode(response.headers.map)),
    key: key,
    lastModified: response.headers[lastModifiedHeader]?.join(','),
    maxStale: checkedMaxStale != null
        ? DateTime.now().toUtc().add(checkedMaxStale)
        : null,
    priority: options.priority,
    requestDate: response.requestOptions.extra[CacheResponse.requestSentDate],
    responseDate: DateTime.now().toUtc(),
    url: response.requestOptions.uri.toString(),
  );
}