-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.js
More file actions
84 lines (75 loc) · 2.2 KB
/
Copy pathvite.config.js
File metadata and controls
84 lines (75 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import {
REALTIME_KLINE_URL,
REALTIME_QUOTE_URL,
REALTIME_TENCENT_URL,
} from './src/analysis/realtimeQuote.js'
const execFileAsync = promisify(execFile)
const marketHeaders = {
accept: 'application/json,*/*',
'user-agent': 'Mozilla/5.0',
}
function writeJson(res, status, payload) {
res.statusCode = status
res.setHeader('content-type', 'application/json; charset=utf-8')
res.setHeader('cache-control', 'no-store')
res.end(JSON.stringify(payload))
}
async function fetchWithCurl(url) {
const { stdout } = await execFileAsync(
'curl',
['--http1.1', '-sS', '--max-time', '8', '-A', marketHeaders['user-agent'], url],
{ maxBuffer: 1024 * 1024 },
)
return stdout
}
async function fetchMarketText(url) {
try {
const response = await fetch(url, { headers: marketHeaders })
const text = await response.text()
if (!response.ok) {
throw new Error(`Upstream market request failed ${response.status}`)
}
return text
} catch {
return fetchWithCurl(url)
}
}
async function proxyMarketJson(res, url) {
try {
const text = await fetchMarketText(url)
res.statusCode = 200
res.setHeader('content-type', 'application/json; charset=utf-8')
res.setHeader('cache-control', 'no-store')
res.end(text)
} catch (error) {
console.error(`[etf-realtime-proxy] upstream request failed: ${url}`, error.message)
writeJson(res, 502, {
rc: 502,
error: '行情代理请求失败',
})
}
}
function realtimeProxyPlugin() {
return {
name: 'etf-realtime-proxy',
configureServer(server) {
server.middlewares.use('/api/realtime/quote', (_req, res) =>
proxyMarketJson(res, REALTIME_QUOTE_URL),
)
server.middlewares.use('/api/realtime/kline', (_req, res) =>
proxyMarketJson(res, REALTIME_KLINE_URL),
)
server.middlewares.use('/api/realtime/tencent', (_req, res) =>
proxyMarketJson(res, REALTIME_TENCENT_URL),
)
},
}
}
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), realtimeProxyPlugin()],
})