diff --git a/cwd-api/src/api/public/getPagePv.ts b/cwd-api/src/api/public/getPagePv.ts index 78351ac..cbf99e2 100644 --- a/cwd-api/src/api/public/getPagePv.ts +++ b/cwd-api/src/api/public/getPagePv.ts @@ -12,11 +12,23 @@ export const getPagePv = async (c: Context<{ Bindings: Bindings }>) => { return c.json({ message: 'post_slug is required' }, 400); } - const row = await c.env.CWD_DB.prepare( - 'SELECT pv FROM page_stats WHERE post_slug = ? AND site_id = ?' - ) - .bind(postSlug, siteId) - .first<{ pv: number }>(); + let row: { pv: number } | null = null; + + if (siteId) { + // 有 siteId 时精确匹配 + 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; diff --git a/docs/widget/src/core/api.js b/docs/widget/src/core/api.js index 14539ce..f3d0eba 100644 --- a/docs/widget/src/core/api.js +++ b/docs/widget/src/core/api.js @@ -122,16 +122,20 @@ export function createApiClient(config) { async function trackVisit() { 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`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - postSlug: config.postUrl || config.postSlug, - postTitle: config.postTitle, - postUrl: config.postUrl - }) + body: JSON.stringify(body) }); } catch (e) { }