-
-
Save manh-t/2bec2fb5f52c6319ac739b9beb2dc62d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'dart:convert'; | |
| import 'package:dio/dio.dart'; | |
| import 'package:dart_jsona/dart_jsona.dart'; | |
| import 'package:flutter/foundation.dart'; | |
| /// Dio Transformer used to automatically serialize and | |
| /// deserialize JSON-API payloads. | |
| class JsonApiTransformer extends DefaultTransformer { | |
| static const kJsonApiMimeType = 'application/vnd.api+json'; | |
| @override | |
| Future<String> transformRequest(RequestOptions options) async { | |
| var data = options.data ?? ''; | |
| if (data is! String) { | |
| if (options.contentType.mimeType == kJsonApiMimeType) { | |
| return _serializeJsonApi(options.data); | |
| } else { | |
| // Fallback to standard JSON encoding if it's not a JSON API payload | |
| return super.transformRequest(options); | |
| } | |
| } | |
| return data.toString(); | |
| } | |
| @override | |
| Future transformResponse( | |
| RequestOptions options, | |
| ResponseBody response, | |
| ) async { | |
| if (response.headers.contentType.mimeType == kJsonApiMimeType) { | |
| var responseBody = await super.transformResponse(options, response); | |
| return _parseJsonApi(responseBody); | |
| } | |
| return super.transformResponse(options, response); | |
| } | |
| } | |
| /// Handles parsing in the background using an isolate | |
| _parseJsonApi(String text) { | |
| return compute(_parseAndDecodeJsonApi, text); | |
| } | |
| /// Decodes a JSON API response | |
| _parseAndDecodeJsonApi(String response) { | |
| return Jsona().deserialize( | |
| jsonDecode(response), | |
| ); | |
| } | |
| /// Serializes a JSON API payload | |
| _serializeJsonApi(dynamic data) { | |
| return jsonEncode( | |
| Jsona().serialize(stuff: data), | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment