Advertisement
Guest User

Untitled

a guest
Sep 11th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. import 'dart:convert';
  2. import 'package:dio/dio.dart';
  3. import 'package:dart_jsona/dart_jsona.dart';
  4. import 'package:flutter/foundation.dart';
  5.  
  6. /// Dio Transformer used to automatically serialize and
  7. /// deserialize JSON-API payloads.
  8. class JsonApiTransformer extends DefaultTransformer {
  9. static const kJsonApiMimeType = 'application/vnd.api+json';
  10.  
  11. @override
  12. Future<String> transformRequest(RequestOptions options) async {
  13. var data = options.data ?? '';
  14. if (data is! String) {
  15. if (options.contentType.mimeType == kJsonApiMimeType) {
  16. return _serializeJsonApi(options.data);
  17. } else {
  18. // Fallback to standard JSON encoding if it's not a JSON API payload
  19. return super.transformRequest(options);
  20. }
  21. }
  22. return data.toString();
  23. }
  24.  
  25. @override
  26. Future transformResponse(
  27. RequestOptions options,
  28. ResponseBody response,
  29. ) async {
  30. if (response.headers.contentType.mimeType == kJsonApiMimeType) {
  31. var responseBody = await super.transformResponse(options, response);
  32. return _parseJsonApi(responseBody);
  33. }
  34.  
  35. return super.transformResponse(options, response);
  36. }
  37. }
  38.  
  39. /// Handles parsing in the background using an isolate
  40. _parseJsonApi(String text) {
  41. return compute(_parseAndDecodeJsonApi, text);
  42. }
  43.  
  44. /// Decodes a JSON API response
  45. _parseAndDecodeJsonApi(String response) {
  46. return Jsona().deserialize(
  47. jsonDecode(response),
  48. );
  49. }
  50.  
  51. /// Serializes a JSON API payload
  52. _serializeJsonApi(dynamic data) {
  53. return jsonEncode(
  54. Jsona().serialize(stuff: data),
  55. );
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement