Revert "重构板块资金流向:行业/概念改用独立 path,后端排序,前端不缓存直接请求"

This reverts commit eea2ce86d0.
This commit is contained in:
Sakurasan
2026-07-13 23:24:26 +08:00
parent eea2ce86d0
commit 22692be45e
3 changed files with 59 additions and 111 deletions
+25 -58
View File
@@ -1,8 +1,4 @@
"""板块数据路由:行业板块、概念板块 """板块数据路由:行业板块、概念板块"""
注意:行业/概念必须走不同 path/industry、/concept),不能仅靠 query 参数区分。
上游反代/CDN 可能按 path 缓存并忽略 query,导致两个 tab 返回相同数据。
"""
from fastapi import APIRouter, Query, HTTPException from fastapi import APIRouter, Query, HTTPException
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
@@ -10,63 +6,34 @@ from services import eastmoney, mootdx
router = APIRouter() router = APIRouter()
# 禁止任何中间层缓存,确保每次请求都打到后端 # 行业/概念通过 query 参数区分,但上游反代/CDN 可能按 path 缓存而忽略 query,
# 导致两个 tab 返回相同数据。显式禁止缓存,保证按 query 区分。
_NO_CACHE_HEADERS = {"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0"} _NO_CACHE_HEADERS = {"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0"}
_SORT_KEYS = {"mainNetInflow", "changePercent"}
@router.get("", summary="板块列表")
async def sector_list(
type: str = Query("industry", description="板块类型:industry=行业板块, concept=概念板块"),
):
if type not in ("industry", "concept"):
raise HTTPException(status_code=400, detail="板块类型错误,仅支持 industry/concept")
def _sort_sectors(data: list[dict], sort: str, order: str) -> list[dict]: data = await eastmoney.fetch_sector_list(type)
"""后端排序:mainNetInflow=资金流入,changePercent=涨幅%"""
reverse = order != "asc"
if sort == "changePercent":
# changePercent 为 None 的排到最后(与方向无关)
return sorted(
data,
key=lambda x: (x.get("changePercent") is None, -(x.get("changePercent") or 0)),
reverse=reverse,
)
return sorted(data, key=lambda x: -(x.get("mainNetInflow") or 0), reverse=reverse)
async def _sector_response(sector_type: str, sort: str, order: str) -> JSONResponse:
data = await eastmoney.fetch_sector_list(sector_type)
source = None
if not data:
# 降级:通达信 mootdx(不含实时资金流数据)
md_data = await mootdx.fetch_sector_list(sector_type)
if md_data:
data = md_data
source = "mootdx"
if data: if data:
data = _sort_sectors(data, sort, order) return JSONResponse(
{"data": data, "count": len(data), "type": type},
headers=_NO_CACHE_HEADERS,
)
payload: dict = {"data": data, "count": len(data), "type": sector_type} # 降级:通达信 mootdx(不含实时资金流数据)
if source: md_data = await mootdx.fetch_sector_list(type)
payload["source"] = source if md_data:
return JSONResponse(payload, headers=_NO_CACHE_HEADERS) return JSONResponse(
{"data": md_data, "count": len(md_data), "type": type, "source": "mootdx"},
headers=_NO_CACHE_HEADERS,
)
return JSONResponse(
@router.get("/industry", summary="行业板块列表") {"data": [], "count": 0, "type": type},
async def sector_industry( headers=_NO_CACHE_HEADERS,
sort: str = Query("mainNetInflow", description="排序字段:mainNetInflow=资金流入, changePercent=涨幅%"), )
order: str = Query("desc", description="排序方向:asc=升序, desc=降序"),
):
if sort not in _SORT_KEYS:
sort = "mainNetInflow"
if order not in ("asc", "desc"):
order = "desc"
return await _sector_response("industry", sort, order)
@router.get("/concept", summary="概念板块列表")
async def sector_concept(
sort: str = Query("mainNetInflow", description="排序字段:mainNetInflow=资金流入, changePercent=涨幅%"),
order: str = Query("desc", description="排序方向:asc=升序, desc=降序"),
):
if sort not in _SORT_KEYS:
sort = "mainNetInflow"
if order not in ("asc", "desc"):
order = "desc"
return await _sector_response("concept", sort, order)
+4 -12
View File
@@ -460,23 +460,15 @@ export interface SectorResponse {
} }
/** /**
* 获取东方财富板块列表 * 获取东方财富板块列表(按主力净流入排序)
* 行业/概念走不同 path/industry、/concept),避免上游反代按 path 缓存忽略 query 导致数据串味
* @param type industry=行业板块, concept=概念板块 * @param type industry=行业板块, concept=概念板块
* @param sort mainNetInflow=资金流入, changePercent=涨幅%
* @param order asc=升序, desc=降序
*/ */
export async function fetchSectors( export async function fetchSectors(type: SectorType, signal?: AbortSignal): Promise<SectorItem[]> {
type: SectorType,
opts?: { sort?: "mainNetInflow" | "changePercent"; order?: "asc" | "desc"; signal?: AbortSignal },
): Promise<SectorItem[]> {
const baseUrl = getApiBaseUrl(); const baseUrl = getApiBaseUrl();
const sort = opts?.sort ?? "mainNetInflow"; const url = `${baseUrl}/api/sectors?type=${type}`;
const order = opts?.order ?? "desc";
const url = `${baseUrl}/api/sectors/${type}?sort=${sort}&order=${order}`;
try { try {
const resp = await fetch(url, { method: "GET", signal: opts?.signal, cache: "no-store" }); const resp = await fetch(url, { method: "GET", signal, cache: "no-store" });
if (!resp.ok) return []; if (!resp.ok) return [];
const result: SectorResponse = await resp.json(); const result: SectorResponse = await resp.json();
return result.data || []; return result.data || [];
+29 -40
View File
@@ -1,5 +1,6 @@
import { createFileRoute, Link } from "@tanstack/react-router"; import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useMemo, useRef, useState } from "react"; import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { fetchSectors, type SectorItem, type SectorType } from "@/lib/stock-api"; import { fetchSectors, type SectorItem, type SectorType } from "@/lib/stock-api";
import { Card, CardContent } from "@/components/ui/card"; import { Card, CardContent } from "@/components/ui/card";
import { ArrowLeft, RefreshCw, ArrowDown, ArrowUp, TrendingUp, TrendingDown } from "lucide-react"; import { ArrowLeft, RefreshCw, ArrowDown, ArrowUp, TrendingUp, TrendingDown } from "lucide-react";
@@ -8,7 +9,7 @@ export const Route = createFileRoute("/sectors")({
component: SectorsPage, component: SectorsPage,
}); });
/* ── Tabs:行业 / 概念(各自独立 path,互不串数据)── */ /* ── Tabs:行业 / 概念 ── */
const TABS: { key: SectorType; label: string }[] = [ const TABS: { key: SectorType; label: string }[] = [
{ key: "industry", label: "行业" }, { key: "industry", label: "行业" },
{ key: "concept", label: "概念" }, { key: "concept", label: "概念" },
@@ -21,27 +22,30 @@ function SectorsPage() {
const [tab, setTab] = useState<SectorType>("industry"); const [tab, setTab] = useState<SectorType>("industry");
const [sortKey, setSortKey] = useState<SortKey>("mainNetInflow"); const [sortKey, setSortKey] = useState<SortKey>("mainNetInflow");
const [asc, setAsc] = useState(true); const [asc, setAsc] = useState(true);
const [data, setData] = useState<SectorItem[]>([]);
const [loading, setLoading] = useState(true);
const abortRef = useRef<AbortController | null>(null);
// 每次 tab / 排序变化都重新发起请求(带 no-store,不缓存) // 行业 / 概念 各自独立的 Query,数据完全隔离,杜绝来回切换时的合并
useEffect(() => { const industryQ = useQuery({
abortRef.current?.abort(); queryKey: ["sectors", "industry"],
const controller = new AbortController(); queryFn: ({ signal }) => fetchSectors("industry", signal),
abortRef.current = controller; staleTime: 30_000,
setLoading(true); retry: false,
fetchSectors(tab, { sort: sortKey, order: asc ? "asc" : "desc", signal: controller.signal }) });
.then((items) => { const conceptQ = useQuery({
if (!controller.signal.aborted) { queryKey: ["sectors", "concept"],
setData(items); queryFn: ({ signal }) => fetchSectors("concept", signal),
setLoading(false); staleTime: 30_000,
} retry: false,
}); });
return () => controller.abort();
}, [tab, sortKey, asc]);
// 后端已按 sort/order 排序;此处再排一次作为兜底,确保 UI 一定响应排序 const { data = [], isLoading, isFetching, refetch } =
tab === "industry" ? industryQ : conceptQ;
// 切换 tab 时强制重新请求,绕过 React Query 缓存和上游反代缓存,确保拿到对应类型的数据
const handleTab = (t: SectorType) => {
setTab(t);
(t === "industry" ? industryQ : conceptQ).refetch();
};
const sorted = useMemo(() => { const sorted = useMemo(() => {
const dir = asc ? 1 : -1; const dir = asc ? 1 : -1;
return [...data].sort((a, b) => { return [...data].sort((a, b) => {
@@ -59,21 +63,6 @@ function SectorsPage() {
} }
}; };
const reload = () => {
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
setLoading(true);
fetchSectors(tab, { sort: sortKey, order: asc ? "asc" : "desc", signal: controller.signal }).then(
(items) => {
if (!controller.signal.aborted) {
setData(items);
setLoading(false);
}
},
);
};
return ( return (
<div className="min-h-screen bg-background"> <div className="min-h-screen bg-background">
{/* 顶栏 */} {/* 顶栏 */}
@@ -86,21 +75,21 @@ function SectorsPage() {
<h1 className="text-base font-semibold"></h1> <h1 className="text-base font-semibold"></h1>
</div> </div>
<button <button
onClick={reload} onClick={() => refetch()}
className="text-muted-foreground hover:text-foreground transition-colors" className="text-muted-foreground hover:text-foreground transition-colors"
> >
<RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} /> <RefreshCw className={`h-4 w-4 ${isFetching ? "animate-spin" : ""}`} />
</button> </button>
</div> </div>
</header> </header>
{/* Tab 切换:行业 / 概念(不同 path 请求) */} {/* Tab 切换:行业 / 概念 */}
<div className="max-w-5xl mx-auto px-4 mt-4"> <div className="max-w-5xl mx-auto px-4 mt-4">
<div className="flex gap-1 bg-muted rounded-lg p-1"> <div className="flex gap-1 bg-muted rounded-lg p-1">
{TABS.map((t) => ( {TABS.map((t) => (
<button <button
key={t.key} key={t.key}
onClick={() => setTab(t.key)} onClick={() => handleTab(t.key)}
className={`flex-1 py-1.5 text-sm font-medium rounded-md transition-colors ${ className={`flex-1 py-1.5 text-sm font-medium rounded-md transition-colors ${
tab === t.key tab === t.key
? "bg-background text-foreground shadow-sm" ? "bg-background text-foreground shadow-sm"
@@ -126,7 +115,7 @@ function SectorsPage() {
{/* 卡片列表 */} {/* 卡片列表 */}
<div className="max-w-5xl mx-auto px-4 mt-3 pb-8"> <div className="max-w-5xl mx-auto px-4 mt-3 pb-8">
{loading ? ( {isLoading ? (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3"> <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
{Array.from({ length: 20 }).map((_, i) => ( {Array.from({ length: 20 }).map((_, i) => (
<div key={i} className="animate-pulse rounded-xl bg-muted h-32" /> <div key={i} className="animate-pulse rounded-xl bg-muted h-32" />