client_base.dart 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. import 'dart:convert';
  2. import 'package:dio/dio.dart' as dio;
  3. import 'package:fis_common/http/http_error.dart';
  4. import 'package:fis_jsonrpc/encrpyt.dart';
  5. import 'package:flutter/foundation.dart';
  6. import 'exception.dart';
  7. import 'http_pool.dart';
  8. import 'interceptor.dart';
  9. import 'request.dart';
  10. // ignore: unused_element
  11. const _C_DIO_FUTURE_ERR_MSG = "Future already completed";
  12. const _C_DIO_FUTURE_ERR_KEYWORDS = "browser_adapter";
  13. /// JSON-RPC Client 基类
  14. class JsonRpcClientBase {
  15. /// 默认超时时间
  16. // ignore: non_constant_identifier_names
  17. static int DEAULT_TIMEOUT = 15000;
  18. /// 请求加密配置
  19. static JsonRpcEncryptConfig requestEncryptConfig = JsonRpcEncryptConfig();
  20. /// 响应加密配置
  21. static JsonRpcEncryptConfig responseEncryptConfig = JsonRpcEncryptConfig();
  22. late int _timeout;
  23. late String _serviceName;
  24. /// 服务主机地址
  25. final String host;
  26. /// 自定义Http header
  27. final Map<String, String>? headers;
  28. /// 超时时间(ms)
  29. int get timeout => _timeout;
  30. /// 服务名称
  31. String get serviceName => _serviceName;
  32. /// 服务请求地址
  33. String get servicePath =>
  34. host.endsWith('/') ? "$host$serviceName" : "$host/$serviceName";
  35. JsonRpcClientBase(
  36. this.host,
  37. String serviceName, {
  38. this.headers,
  39. int? timeout,
  40. }) {
  41. _timeout = timeout ?? DEAULT_TIMEOUT;
  42. _serviceName = serviceName;
  43. }
  44. void setTimeout(int milliseconds) {}
  45. /// 设置服务名
  46. void setServiceName(String name) => _serviceName = name;
  47. /// 请求RPC method
  48. @protected
  49. Future<dynamic> call(String method, [args]) async {
  50. var request = JsonRpcRequest(method, args);
  51. return _transmit(request);
  52. }
  53. /// 通知 RPC method
  54. @protected
  55. void notify(String method, [args]) {
  56. var request = JsonRpcRequest(method, args, notify: true);
  57. _transmit(request);
  58. }
  59. Future<dynamic> _transmit(JsonRpcRequest request) async {
  60. var result;
  61. try {
  62. final req = await jsonRpcInterceptHost.onRequestTransmit(request);
  63. String package = jsonEncode(req.toJson());
  64. var response = await _postRequest(package);
  65. if (response == null) throw JsonRpcException(message: "Response Empty");
  66. result = await _handleDecoded(response);
  67. } catch (e) {
  68. if (e is FHttpError)
  69. await _handleHttpRequestError(JsonRpcNetworkException(e.toString()));
  70. throw JsonRpcException(message: "Http error", data: e);
  71. }
  72. return result;
  73. }
  74. Future<dynamic> _postRequest(String package) async {
  75. try {
  76. final httpClient = jrpcHttpPool.getClient(
  77. this.host,
  78. timeout: this.timeout,
  79. headers: this.headers,
  80. );
  81. var response =
  82. await httpClient.post('/${this.serviceName}', data: package);
  83. if (response.statusCode != 200) {
  84. throw JsonRpcException(
  85. message: "Http error.Status coder: ${response.statusCode}.");
  86. }
  87. return response.data;
  88. } on dio.DioError catch (e) {
  89. throw JsonRpcException(message: "Http error", data: e);
  90. } on StateError catch (e) {
  91. if (e.message == _C_DIO_FUTURE_ERR_MSG) {
  92. if (e.stackTrace != null &&
  93. e.stackTrace.toString().contains(_C_DIO_FUTURE_ERR_KEYWORDS)) {
  94. // don't rethrow
  95. }
  96. }
  97. }
  98. }
  99. Future<dynamic> _handleHttpRequestError(JsonRpcNetworkException error) async {
  100. final res = await jsonRpcInterceptHost.onHttpRequestError(error);
  101. throw res;
  102. }
  103. Future<dynamic> _handleDecoded(Map<String, dynamic> response) async {
  104. final res = await jsonRpcInterceptHost.onResponse(response);
  105. if (res.containsKey('error')) {
  106. var error = JsonRpcServerError.fromJson(res['error']);
  107. error = await jsonRpcInterceptHost.onResponseError(error);
  108. throw error;
  109. }
  110. var result = res['result'];
  111. result = await jsonRpcInterceptHost.onResponseResult(result);
  112. return result;
  113. }
  114. }
  115. abstract class JsonRpcRequestModelBase {
  116. /// 转成Json Map
  117. Map<String, dynamic> toJson();
  118. }