openapi_extensions.dart 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. }) async {
  19. final response = await getAllAssetsWithHttpInfo(
  20. ifNoneMatch: eTag,
  21. userId: userId,
  22. isFavorite: isFavorite,
  23. isArchived: isArchived,
  24. );
  25. if (response.statusCode >= HttpStatus.badRequest) {
  26. throw ApiException(response.statusCode, await _decodeBodyBytes(response));
  27. }
  28. // When a remote server returns no body with a status of 204, we shall not decode it.
  29. // At the time of writing this, `dart:convert` will throw an "Unexpected end of input"
  30. // FormatException when trying to decode an empty string.
  31. if (response.body.isNotEmpty &&
  32. response.statusCode != HttpStatus.noContent) {
  33. final responseBody = await _decodeBodyBytes(response);
  34. final etag = response.headers[HttpHeaders.etagHeader];
  35. final data = (await apiClient.deserializeAsync(
  36. responseBody,
  37. 'List<AssetResponseDto>',
  38. ) as List)
  39. .cast<AssetResponseDto>()
  40. .toList();
  41. return (data, etag);
  42. }
  43. return (null, null);
  44. }
  45. }
  46. /// Returns the decoded body as UTF-8 if the given headers indicate an 'application/json'
  47. /// content type. Otherwise, returns the decoded body as decoded by dart:http package.
  48. Future<String> _decodeBodyBytes(Response response) async {
  49. final contentType = response.headers['content-type'];
  50. return contentType != null &&
  51. contentType.toLowerCase().startsWith('application/json')
  52. ? response.bodyBytes.isEmpty
  53. ? ''
  54. : utf8.decode(response.bodyBytes)
  55. : response.body;
  56. }