service_node.dart 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import 'dart:convert';
  2. /// 服务节点(线路)
  3. class ServiceNode {
  4. final int id;
  5. final String name;
  6. final String apiHost;
  7. final String wsHost;
  8. final int status;
  9. const ServiceNode({
  10. required this.id,
  11. required this.name,
  12. required this.apiHost,
  13. required this.wsHost,
  14. this.status = 0,
  15. });
  16. factory ServiceNode.fromJson(Map<String, dynamic> json) {
  17. return ServiceNode(
  18. id: json['id'] as int? ?? 0,
  19. name: json['name'] as String? ?? '',
  20. apiHost: json['apiHost'] as String? ?? '',
  21. wsHost: json['wsHost'] as String? ?? '',
  22. status: json['status'] as int? ?? 0,
  23. );
  24. }
  25. Map<String, dynamic> toJson() => {
  26. 'id': id,
  27. 'name': name,
  28. 'apiHost': apiHost,
  29. 'wsHost': wsHost,
  30. 'status': status,
  31. };
  32. /// apiHost 是否为有效 URL
  33. bool get isValid =>
  34. apiHost.startsWith('http') && wsHost.startsWith('ws');
  35. /// 归一化 API Host:确保以 / 结尾,以便 Dio 正确拼接相对路径
  36. /// 例如 "https://xxx.top/api" → "https://xxx.top/api/"
  37. String get normalizedApiHost {
  38. var host = apiHost;
  39. if (!host.endsWith('/')) host = '$host/';
  40. return host;
  41. }
  42. /// 归一化 WS Host:补全 /ws/market 后缀
  43. /// 例如 "ws://xxx.top/api/market-new" → "ws://xxx.top/api/market-new/ws/market"
  44. String get normalizedWsHost {
  45. var host = wsHost;
  46. if (!host.endsWith('/ws/market')) {
  47. if (host.endsWith('/')) host = host.substring(0, host.length - 1);
  48. host = '$host/ws/market';
  49. }
  50. return host;
  51. }
  52. /// 从 JSON 字符串列表反序列化
  53. static List<ServiceNode> listFromJson(String jsonStr) {
  54. final list = jsonDecode(jsonStr) as List<dynamic>;
  55. return list
  56. .map((e) => ServiceNode.fromJson(e as Map<String, dynamic>))
  57. .toList();
  58. }
  59. /// 序列化列表为 JSON 字符串
  60. static String listToJson(List<ServiceNode> nodes) {
  61. return jsonEncode(nodes.map((e) => e.toJson()).toList());
  62. }
  63. }