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