perf(packages): 优化 /api/packages 7000+ 条响应性能
- buildPackages 缓存全量结果(rawCache/ignored/threshold 不变时复用) - gzip 压缩大响应(Node 内置 zlib,减少传输体积 60-80%)
This commit is contained in:
@@ -20,6 +20,7 @@ process.env.UV_THREADPOOL_SIZE = process.env.UV_THREADPOOL_SIZE || '8'
|
||||
import express from 'express'
|
||||
import path from 'node:path'
|
||||
import fs from 'node:fs'
|
||||
import zlib from 'node:zlib'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { resolveStorageDir } from './scanner.js'
|
||||
import { isDemoMode, scanState, runScanAsync } from './scan-manager.js'
|
||||
@@ -40,6 +41,26 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
const app = express()
|
||||
app.use(express.json({ limit: '1mb' }))
|
||||
|
||||
// gzip 压缩:大响应(如 /api/packages 7000+ 条)减少传输体积 60-80%,Node 内置 zlib 无需新依赖
|
||||
app.use((req, res, next) => {
|
||||
const accept = req.headers['accept-encoding'] || ''
|
||||
if (!accept.includes('gzip')) return next()
|
||||
const originalJson = res.json.bind(res)
|
||||
res.json = (data) => {
|
||||
try {
|
||||
const json = JSON.stringify(data)
|
||||
if (json.length < 1024) return originalJson(data) // 小响应不压缩,避免开销
|
||||
const compressed = zlib.gzipSync(json)
|
||||
res.setHeader('Content-Encoding', 'gzip')
|
||||
res.setHeader('Content-Type', 'application/json')
|
||||
res.send(compressed)
|
||||
} catch {
|
||||
originalJson(data)
|
||||
}
|
||||
}
|
||||
next()
|
||||
})
|
||||
|
||||
const PORT = Number(process.env.PORT || 3000)
|
||||
|
||||
// —— 路由装配:登录/登出/主题公开,其余 /api/* 需鉴权 ——
|
||||
|
||||
Reference in New Issue
Block a user