101 lines
2.8 KiB
JavaScript
Raw Normal View History

2025-11-18 17:53:04 +08:00
import { newImageMarkTooltip } from '../components/ImageMarkTooltip'
// 专门用于绘制图片的api数据类
export default class ImageMarkData {
key = null
markerIcon = null
api = null
// 提示框实例,当鼠标移入或者点击图例时,需要获取到该实例
tooltip = null
onResponse = null
cacheData = null
expiresAt = null
abortController = null
2025-11-19 17:47:20 +08:00
loading = false
2025-11-18 17:53:04 +08:00
/**
* 60秒内重复点击使用缓存数据减少服务器压力
*/
cacheTime = 60 * 1000
2025-11-19 17:47:20 +08:00
constructor({ api, tooltip, markerIcon, onResponse, key }) {
2025-11-18 17:53:04 +08:00
this.api = api
2025-11-19 17:47:20 +08:00
this.key = key
2025-11-18 17:53:04 +08:00
this.response = onResponse
2025-11-19 17:47:20 +08:00
this.markerIcon = markerIcon
2025-11-18 17:53:04 +08:00
// 初始化提示框
2025-11-19 17:47:20 +08:00
this.tooltip = tooltip || newImageMarkTooltip({key})
2025-11-18 17:53:04 +08:00
}
getCache = () => {
// 检查缓存是否有效
if (
this.cacheData?.length &&
this.expiresAt > Date.now()
) {
return this.cacheData
}
}
request = async (params) => {
// 首先查看缓存是否可用
const cacheData = this.getCache()
if (cacheData) return cacheData
2025-11-19 17:47:20 +08:00
this.loading = true
2025-11-18 17:53:04 +08:00
const controller = this.createAbortController()
const config = {}
if (controller) config.signal = controller.signal
let res = null
try {
res = await this.api(params, config)
} catch (error) {
console.error('请求失败: ', error)
} finally {
2025-11-19 17:47:20 +08:00
this.loading = false
2025-11-18 17:53:04 +08:00
let data = null
if (this.response) data = this.response(res)
else data = this.commonOnResponse(res)
this.cacheData = data
this.expiresAt = Date.now() + this.cacheTime
return data
}
}
createAbortController = () => {
if (typeof AbortController === 'undefined') {
console.warn('当前环境不支持 AbortController')
return null
}
return new AbortController()
}
cancelRequest = () => {
if (this.abortController) {
try {
this.abortController.abort()
} catch (error) {
this.console.warn('取消请求失败', error)
} finally {
this.abortController = null
}
}
}
// 通用的响应处理
commonOnResponse = (res) => {
if (res?.success) {
const dataList = res.data.map((item) => {
item.mapData = {
id: this.key + '-' + item.rid,
layerId: this.key,
position: [item.jd, item.wd, 0],
image: this.markerIcon
}
return item
})
return dataList
}
return []
}
}