fix(widget): 修复页面访问量获取失败的问题

- 前端 trackVisit 现在传递 siteId 参数
- 后端 getPagePv 查询时处理 site_id 为空或 NULL 的情况
This commit is contained in:
anghunk
2026-03-16 14:09:59 +08:00
parent e2db5daecb
commit 2ad9c90d18
2 changed files with 26 additions and 10 deletions

View File

@@ -12,11 +12,23 @@ export const getPagePv = async (c: Context<{ Bindings: Bindings }>) => {
return c.json({ message: 'post_slug is required' }, 400); return c.json({ message: 'post_slug is required' }, 400);
} }
const row = await c.env.CWD_DB.prepare( let row: { pv: number } | null = null;
'SELECT pv FROM page_stats WHERE post_slug = ? AND site_id = ?'
) if (siteId) {
.bind(postSlug, siteId) // 有 siteId 时精确匹配
.first<{ pv: number }>(); row = await c.env.CWD_DB.prepare(
'SELECT pv FROM page_stats WHERE post_slug = ? AND site_id = ?'
)
.bind(postSlug, siteId)
.first<{ pv: number }>();
} else {
// 无 siteId 时,匹配空字符串或 NULL
row = await c.env.CWD_DB.prepare(
'SELECT pv FROM page_stats WHERE post_slug = ? AND (site_id = ? OR site_id IS NULL)'
)
.bind(postSlug, '')
.first<{ pv: number }>();
}
const pv = row?.pv || 0; const pv = row?.pv || 0;

View File

@@ -122,16 +122,20 @@ export function createApiClient(config) {
async function trackVisit() { async function trackVisit() {
try { try {
const body = {
postSlug: config.postUrl || config.postSlug,
postTitle: config.postTitle,
postUrl: config.postUrl
};
if (config.siteId) {
body.siteId = config.siteId;
}
await fetch(`${baseUrl}/api/analytics/visit`, { await fetch(`${baseUrl}/api/analytics/visit`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
body: JSON.stringify({ body: JSON.stringify(body)
postSlug: config.postUrl || config.postSlug,
postTitle: config.postTitle,
postUrl: config.postUrl
})
}); });
} catch (e) { } catch (e) {
} }