rpc.dart 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import 'package:fis_jsonrpc/rpc.dart';
  2. import 'package:vitalapp/architecture/utils/json_rpc_ex_interceptor.dart';
  3. import 'package:vitalapp/global.dart';
  4. import 'package:vitalapp/mock/mock.dart';
  5. final _host = _ProxyHost();
  6. abstract class RpcSettingCache {
  7. static String hostPath = "http://127.0.0.1:80";
  8. static void setRpcHostPath(String path) {
  9. hostPath = path;
  10. final uri = Uri.parse(hostPath);
  11. rpc.setServerHost("${uri.host}:${uri.port}", uri.scheme == 'https');
  12. rpc.clearCache();
  13. }
  14. }
  15. /// JSON-RPC client proxy
  16. JsonRpcProxy get rpc => _host.getProxy();
  17. class _ProxyHost {
  18. JsonRpcProxy? _proxy;
  19. final JsonRpcProxy _mockProxy = JsonRpcMockProxy()
  20. ..setServerHost(RpcSettingCache.hostPath);
  21. /// JSON-RPC client
  22. JsonRpcProxy getProxy() {
  23. if (kIsOnline == false) {
  24. return _mockProxy;
  25. }
  26. if (_proxy == null) {
  27. _init();
  28. }
  29. return _proxy!;
  30. }
  31. /// 初始化代理
  32. void _init() {
  33. _buildProxy();
  34. // _listenServerHostChange();
  35. }
  36. /// 构建代理实例
  37. void _buildProxy() {
  38. final originServerHost =
  39. _proxy?.currentHostAddress ?? RpcSettingCache.hostPath;
  40. JsonRpcProxy jsonRpcProxy = JsonRpcProxy();
  41. _proxy = jsonRpcProxy;
  42. if (originServerHost.isNotEmpty) {
  43. _setRpcHost(_proxy!, originServerHost);
  44. }
  45. // _proxy!.addInterceptor(_DefaultInterceptor());
  46. _proxy!.addInterceptor(JsonRpcExInterceptor());
  47. }
  48. // /// 监听服务地址变更
  49. // void _listenServerHostChange() {
  50. // bus.on(bus.Keys.SERVER_ADDRESS_CHANGED, (arg) {
  51. // logger.i('EventBus - [${bus.Keys.SERVER_ADDRESS_CHANGED}]: $arg');
  52. // _setRpcHost(rpc, arg);
  53. // rpc.clearCache();
  54. // });
  55. // }
  56. static void _setRpcHost(JsonRpcProxy rpc, url) {
  57. final uri = Uri.parse(url);
  58. rpc.setServerHost("${uri.host}:${uri.port}", uri.scheme == "https");
  59. }
  60. }
  61. extension JsonRpcProxyExt on JsonRpcProxy {
  62. JsonRpcProxy get mock => _host._mockProxy;
  63. }