openapi_extensions.dart 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:http/http.dart';
  4. import 'package:openapi/api.dart';
  5. import 'tuple.dart';
  6. /// Extension methods to retrieve ETag together with the API call
  7. extension WithETag on AssetApi {
  8. /// Get all AssetEntity belong to the user
  9. ///
  10. /// Parameters:
  11. ///
  12. /// * [String] eTag:
  13. /// ETag of data already cached on the client
  14. Future<Pair<List<AssetResponseDto>, String?>?> getAllAssetsWithETag({
  15. String? eTag,
  16. }) async {
  17. final response = await getAllAssetsWithHttpInfo(
  18. ifNoneMatch: eTag,
  19. );
  20. if (response.statusCode >= HttpStatus.badRequest) {
  21. throw ApiException(response.statusCode, await _decodeBodyBytes(response));
  22. }
  23. // When a remote server returns no body with a status of 204, we shall not decode it.
  24. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input"
  25. // FormatException when trying to decode an empty string.
  26. if (response.body.isNotEmpty &&
  27. response.statusCode != HttpStatus.noContent) {
  28. final responseBody = await _decodeBodyBytes(response);
  29. final etag = response.headers[HttpHeaders.etagHeader];
  30. final data = (await apiClient.deserializeAsync(
  31. responseBody, 'List<AssetResponseDto>') as List)
  32. .cast<AssetResponseDto>()
  33. .toList();
  34. return Pair(data, etag);
  35. }
  36. return null;
  37. }
  38. }
  39. /// Returns the decoded body as UTF-8 if the given headers indicate an 'application/json'
  40. /// content type. Otherwise, returns the decoded body as decoded by dart:http package.
  41. Future<String> _decodeBodyBytes(Response response) async {
  42. final contentType = response.headers['content-type'];
  43. return contentType != null &&
  44. contentType.toLowerCase().startsWith('application/json')
  45. ? response.bodyBytes.isEmpty
  46. ? ''
  47. : utf8.decode(response.bodyBytes)
  48. : response.body;
  49. }