openapi_extensions.dart 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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,
  32. 'List<AssetResponseDto>',
  33. ) as List)
  34. .cast<AssetResponseDto>()
  35. .toList();
  36. return Pair(data, etag);
  37. }
  38. return null;
  39. }
  40. }
  41. /// Returns the decoded body as UTF-8 if the given headers indicate an 'application/json'
  42. /// content type. Otherwise, returns the decoded body as decoded by dart:http package.
  43. Future<String> _decodeBodyBytes(Response response) async {
  44. final contentType = response.headers['content-type'];
  45. return contentType != null &&
  46. contentType.toLowerCase().startsWith('application/json')
  47. ? response.bodyBytes.isEmpty
  48. ? ''
  49. : utf8.decode(response.bodyBytes)
  50. : response.body;
  51. }