request.dart 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import 'package:fis_jsonrpc/utils.dart';
  2. class JsonRpcRequest {
  3. static const String _serverVersion = '2.0';
  4. final String method;
  5. final Object? args;
  6. final bool notify;
  7. int? get id => !this.notify ? this.hashCode : null;
  8. JsonRpcRequest(this.method, this.args, {this.notify = false});
  9. Map<String, dynamic> toJson() {
  10. var map = <String, dynamic>{};
  11. map = {
  12. 'jsonrpc': _serverVersion,
  13. 'method': method,
  14. 'params': _buildParams(),
  15. };
  16. if (!notify) map['id'] = id;
  17. return map;
  18. }
  19. bool _isComplexType(dynamic v) {
  20. if (v is String) return false;
  21. if (v is num) return false;
  22. if (v is bool) return false;
  23. if (v is Symbol) return false;
  24. if (v is List) return false;
  25. if (v is Map) return false;
  26. if (v is Set) return false;
  27. return true;
  28. }
  29. dynamic _doComplexValToJson(dynamic v) {
  30. if (v is DateTime) {
  31. return JsonRpcUtils.dateFormat(v);
  32. }
  33. dynamic fn;
  34. try {
  35. fn = v.toJson;
  36. } catch (e) {
  37. try {
  38. final idx = v.index;
  39. fn = () => idx;
  40. } catch (e) {
  41. fn = () => null;
  42. }
  43. }
  44. return fn();
  45. }
  46. List _buildListParams() {
  47. final arr = (args as List);
  48. for (var i = 0; i < arr.length; i++) {
  49. final v = arr[i];
  50. if (_isComplexType(v)) {
  51. arr[i] = _doComplexValToJson(v);
  52. }
  53. }
  54. return arr;
  55. }
  56. Map _buildMapParams() {
  57. final map = (args as Map);
  58. map.forEach((k, v) {
  59. if (_isComplexType(v)) {
  60. map[k] = _doComplexValToJson(v);
  61. }
  62. });
  63. return map;
  64. }
  65. List _buildSetParams() {
  66. final set = (args as Set);
  67. final arr = [];
  68. set.forEach((v) {
  69. if (_isComplexType(v)) {
  70. arr.add(_doComplexValToJson(v));
  71. } else {
  72. arr.add(v);
  73. }
  74. });
  75. return arr;
  76. }
  77. dynamic _buildParams() {
  78. if (args == null) return [];
  79. if (args is List) {
  80. return _buildListParams();
  81. }
  82. if (args is Map) {
  83. return _buildMapParams();
  84. }
  85. if (args is Set) {
  86. return _buildSetParams();
  87. }
  88. return [args];
  89. }
  90. @override
  91. String toString() => 'JsonRpcRequest: ${toJson()}';
  92. }