openapi_extensions.dart 2.1 KB

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