Created
August 31, 2019 15:22
-
-
Save jamesdixon/934f20410c24a89695e101eca001f0ac 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