fix: update
This commit is contained in:
@@ -14,6 +14,9 @@ const openApiSpec = require('./openapi')
|
||||
const app = express()
|
||||
const PORT = process.env.API_PORT || 3001
|
||||
|
||||
// 爬虫通知用的共享密钥:API_CRAWLER_TOKEN(仅在服务端与爬虫进程间传递)
|
||||
const CRAWLER_TOKEN = process.env.API_CRAWLER_TOKEN || ''
|
||||
|
||||
app.set('trust proxy', 1)
|
||||
app.use(cors())
|
||||
app.use(express.json())
|
||||
@@ -23,7 +26,14 @@ app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(openApiSpec))
|
||||
|
||||
app.use('/api', routes)
|
||||
app.get('/api/health', (_, res) => res.json({ ok: true }))
|
||||
app.post('/api/crawler/notify', (_, res) => {
|
||||
app.post('/api/crawler/notify', (req, res) => {
|
||||
// 若配置了 API_CRAWLER_TOKEN,则要求爬虫携带 X-Crawler-Token 头
|
||||
if (CRAWLER_TOKEN) {
|
||||
const token = req.headers['x-crawler-token']
|
||||
if (typeof token !== 'string' || token !== CRAWLER_TOKEN) {
|
||||
return res.status(401).json({ error: 'unauthorized' })
|
||||
}
|
||||
}
|
||||
notifyCrawlerUpdate()
|
||||
res.json({ ok: true })
|
||||
})
|
||||
@@ -59,13 +69,18 @@ function broadcastSituation() {
|
||||
app.set('broadcastSituation', broadcastSituation)
|
||||
setInterval(broadcastSituation, 3000)
|
||||
|
||||
// 供爬虫调用:更新 situation.updated_at 并立即广播
|
||||
// 供爬虫调用:先从磁盘重载 DB(纳入爬虫写入),再更新 updated_at 并立即广播
|
||||
function notifyCrawlerUpdate() {
|
||||
try {
|
||||
const db = require('./db')
|
||||
db.reloadFromFile()
|
||||
db.prepare("INSERT OR REPLACE INTO situation (id, data, updated_at) VALUES (1, '{}', ?)").run(new Date().toISOString())
|
||||
broadcastSituation()
|
||||
} catch (_) {}
|
||||
const n = db.prepare('SELECT COUNT(*) as c FROM situation_update').get().c
|
||||
console.log('[crawler/notify] DB 已重载并广播,situation_update 条数:', n)
|
||||
} catch (e) {
|
||||
console.error('[crawler/notify]', e?.message || e)
|
||||
}
|
||||
}
|
||||
|
||||
db.initDb().then(() => {
|
||||
|
||||
Reference in New Issue
Block a user