import React, { Component } from 'react'; import { GlobalItemProp } from '../App'; import { ConfigListProp,ConfigItemProp, RequestMethod } from './chart.d'; import { DataSourceType, RequestDataType } from './chartFactory.d'; import styles from "./index.module.css"; import {getPropertyValue, getUrlParam} from './utils'; /** 单次数据请求超时时长(毫秒),超时后进入下一次轮询 */ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000; interface Prop { contentRender : (remoteData:any,originData:GlobalItemProp,parentEle?:HTMLDivElement)=>React.ReactElement ; data : GlobalItemProp ; style : React.CSSProperties ; debug ?: boolean ; } interface State { data : any ; } export default class RemoteDataHOC extends Component { timer : any = undefined ; /** 当前进行中的请求,用于超时与组件卸载时中断 */ activeFetchController : AbortController | null = null ; div : HTMLDivElement|null = null ; state : State = { data : undefined , } getDataWithData = ()=>{ this.requestData(); } closeTimer = ()=>{ if (this.timer !== undefined) { clearTimeout(this.timer); this.timer = undefined; } } componentWillUnmount(){ this.closeTimer() if (this.activeFetchController) { this.activeFetchController.abort(); this.activeFetchController = null; } } /** 在「刷新时间」后发起下一次请求;刷新时间以图表配置为准,缺省与图表默认一致 5000ms */ scheduleNextRefresh = ()=>{ const {data} = this.props; const requestConfig : ConfigListProp|undefined = data.data.data?.config; const v = getPropertyValue(requestConfig,"刷新时间"); const delay = typeof v === "number" && v >= 0 ? v : 5000; this.closeTimer(); this.timer = window.setTimeout(()=>{ this.requestData(); }, delay); } /** 带超时的 fetch,与组件生命周期绑定 */ fetchWithTimeout = (input: RequestInfo, init: RequestInit = {}): Promise=>{ const controller = new AbortController(); this.activeFetchController = controller; const c = controller; const timeoutId = window.setTimeout(()=>{ c.abort(); }, DEFAULT_REQUEST_TIMEOUT_MS); return fetch(input, { ...init, signal: c.signal }) .finally(()=>{ clearTimeout(timeoutId); if (this.activeFetchController === c) { this.activeFetchController = null; } }); } requestData = ()=>{ const {data} = this.props; const requestConfig : ConfigListProp|undefined = data.data.data?.config; try { // 数据类型 const dataType : string = getPropertyValue(requestConfig,"数据类型"); // 接口地址 let url : string = getPropertyValue(requestConfig,"接口地址"); // 接口方法 const method : string = getPropertyValue(requestConfig,"接口方式"); // 参数编辑 let p : any = undefined ; let dataParam : string = getPropertyValue(requestConfig,"参数编辑"); const urlParam = getUrlParam(); eval(`dataParam=\`${dataParam}\``) if(dataParam==''){ dataParam = "{}"; } if(dataType == DataSourceType.静态数据){ this.setData(dataParam); this.scheduleNextRefresh(); return ; } p = JSON.parse(dataParam); console.log("开始请求数据\n"+url) const onCycleEnd = ()=>{ this.scheduleNextRefresh(); }; const run = (pReq: Promise | undefined)=>{ if (pReq) { pReq.catch((e: Error)=>{ if (e && (e as any).name === "AbortError") { console.log("数据请求超时或已取消"); } else { console.log("数据请求失败", e); } }).finally(onCycleEnd); } else { onCycleEnd(); } }; switch(method){ case RequestMethod.get: return run(this.getData(url,p)); case RequestMethod.post: return run(this.postData(url,p)); default: console.log("不支持请求方法"); return onCycleEnd(); } } catch (e) { console.log("数据请求准备阶段失败", e); this.scheduleNextRefresh(); } } getData = (url:string,param:object): Promise=>{ return this.fetchWithTimeout(url,{ method:"get",credentials:"include", mode:"cors"}) .then(res=>res.json()) .then(res=>{ this.handleForResponse(url,param,res) }) } convertUrlProtocolToCurrent = (targetUrl:string) => { // 获取当前页面的协议(http: 或 https:) const currentProtocol = window.location.protocol; // 处理无协议或协议已匹配的情况(直接返回) if (!targetUrl || targetUrl.startsWith('//') || targetUrl.startsWith(currentProtocol)) { return targetUrl; } // 处理相对路径(如 /api/data) if (targetUrl.startsWith('/')) { return `${currentProtocol}//${window.location.host}${targetUrl}`; } // 处理完整URL(替换协议) try { const urlObj = new URL(targetUrl); urlObj.protocol = currentProtocol; return urlObj.toString(); } catch (e) { // 如果URL解析失败(如格式错误),返回原始URL console.warn('URL解析失败:', targetUrl); return targetUrl; } } postData = (url:string,param:object): Promise=>{ const final_url = this.convertUrlProtocolToCurrent(url); return this.fetchWithTimeout(final_url,{ method:"post", body:JSON.stringify(param), headers:{ "Content-Type":"application/json" }, credentials:'omit', mode:"cors" }) .then(res=>res.json()) .then(res=>{ this.handleForResponse(url,param,res) }) } handleForResponse = (url:string,param:object,res:any)=>{ this.setData(res) } setData = (data:any)=>{ this.setState({data}) } componentDidMount(){ this.getDataWithData(); } renderSub = (remoteData:any,config:GlobalItemProp)=>{ return this.props.contentRender(remoteData,config,this.div||undefined); } render(){ const {style} = this.props; const {data} = this.state; return (
this.div=ref}> {(data||data=='')?this.renderSub(data,this.props.data):null}
) } }