SOURCE

// DataComponent 接口定义(供参考)
/*
interface DataComponent {
  id: string;
  fetchDataConfig: {
    url: string;
    method: "GET" | "POST";
    params: Record<string, any>;
  };
  frequency: "low" | "medium" | "high";
  onDataUpdated: (newData: any) => void;
}
*/

class DataHubClient {
  constructor(serverUrl) {
    this.serverUrl = serverUrl; // 例如 wss://your-server-domain/hub
    this.componentMap = new Map(); // key -> { component, fetchDataConfig, frequency }
    this.ws = null;
    this.reconnectAttempts = 0;
    this.maxReconnect = 3;
    this.connect();
  }

  // 生成唯一 key
  static genKey(component) {
    return `${component.id}_${component.fetchDataConfig.url}_${JSON.stringify(component.fetchDataConfig.params)}_${component.frequency}`;
  }

  // 注册组件
  registerComponent(component) {
    const key = DataHubClient.genKey(component);
    this.componentMap.set(key, {
      component,
      fetchDataConfig: component.fetchDataConfig,
      frequency: component.frequency,
    });
    this.sendRegister(key, component);
  }

  // 发送注册信息
  sendRegister(key, component) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify({
        type: "REGISTER",
        data: {
          key,
          componentId: component.id,
          fetchConfig: component.fetchDataConfig,
          frequency: component.frequency,
        }
      }));
    }
  }

  // 建立 WebSocket 连接
  connect() {
    this.ws = new WebSocket(this.serverUrl);
    this.ws.onopen = () => {
      this.reconnectAttempts = 0;
      // 重新同步所有注册组件
      for (const [key, { component }] of this.componentMap.entries()) {
        this.sendRegister(key, component);
      }
    };
    this.ws.onmessage = (event) => {
      const msg = JSON.parse(event.data);
      if (msg.type === "DATA_UPDATE") {
        const { key, newData } = msg;
        const info = this.componentMap.get(key);
        if (info) {
          info.component.onDataUpdated(newData);
        }
      }
    };
    this.ws.onclose = () => {
      if (this.reconnectAttempts < this.maxReconnect) {
        setTimeout(() => {
          this.reconnectAttempts++;
          this.connect();
        }, 5000);
      }
    };
  }
}

// 用法示例
const client = new DataHubClient("ws://localhost:8080/hub"); // 本地测试用 ws://
client.registerComponent({
  id: "weather-widget",
  fetchDataConfig: {
    url: "https://api.weather.com/current",
    method: "GET",
    params: { city: "beijing" }
  },
  frequency: "low",
  onDataUpdated: (data) => {
    console.log("天气数据更新:", data);
  }
}); 
console 命令行工具 X clear

                    
>
console