feat: add pageview

This commit is contained in:
KazooTTT
2024-11-23 21:09:37 +08:00
parent 4afdf7572a
commit ff5a3a50bd
9 changed files with 295 additions and 87 deletions

View File

@ -0,0 +1,79 @@
import { useEffect, useState } from 'react';
interface PageViewsProps {
slug: string;
}
export default function PageViews({ slug }: PageViewsProps) {
const [views, setViews] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchData = async () => {
try {
// Get initial views
const getResponse = await fetch(`/api/pageview/${slug}`);
if (!getResponse.ok) {
const errorData = await getResponse.json();
console.error('Error getting views:', errorData);
setError('Failed to get views');
return;
}
const getData = await getResponse.json();
setViews(getData.views);
// Increment views
const postResponse = await fetch(`/api/pageview/${slug}`, {
method: 'POST',
});
if (!postResponse.ok) {
const errorData = await postResponse.json();
console.error('Error incrementing views:', errorData);
return;
}
const postData = await postResponse.json();
setViews(postData.views);
} catch (error) {
console.error('Error with page views:', error);
setError('Failed to load views');
}
};
fetchData();
}, [slug]);
if (error) {
console.error('Page views error:', error);
return null;
}
if (views === null) {
return null;
}
return (
<div className="flex items-center gap-1 text-sm text-gray-500">
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-4 w-4"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
/>
</svg>
<span>{views} views</span>
</div>
);
}

View File

@ -5,6 +5,7 @@ import BlogHero from '@/components/blog/Hero.astro'
import TOC from '@/components/blog/TOC.astro'
import Button from '@/components/Button.astro'
import PageLayout from './BaseLayout.astro'
import PageViews from '@/components/PageViews'
interface Props {
post: CollectionEntry<'post'>
@ -41,7 +42,12 @@ const { headings } = await post.render()
<div class='mt-8 gap-x-10 lg:flex lg:items-start'>
{!!headings.length && <TOC headings={headings} />}
<article class='flex-1 flex-grow break-words' data-pagefind-body>
<div id='blog-hero'><BlogHero content={post} /></div>
<div id='blog-hero'>
<BlogHero content={post} />
<div class="mt-2">
<PageViews client:load slug={slug} />
</div>
</div>
<div
id='blog-gallery'
class='prose prose-base prose-zinc mt-12 text-muted-foreground dark:prose-invert prose-headings:font-medium prose-headings:text-foreground prose-headings:before:absolute prose-headings:before:-ms-4 prose-th:before:content-none'

View File

@ -0,0 +1,147 @@
import type { APIRoute } from 'astro';
export const GET: APIRoute = async ({ params, locals, request }) => {
const slug = params.slug;
if (!slug) {
return new Response(JSON.stringify({ error: 'Slug is required' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
});
}
// Access runtime environment through context
const ctx = locals as any;
const env = ctx.env || ctx.runtime?.env;
console.log('Context:', {
hasEnv: !!ctx.env,
hasRuntime: !!ctx.runtime,
envKeys: ctx.env ? Object.keys(ctx.env) : [],
runtimeEnvKeys: ctx.runtime?.env ? Object.keys(ctx.runtime.env) : []
});
const db = env?.DB;
if (!db) {
console.error('D1 database not available');
return new Response(
JSON.stringify({
error: 'Database not configured',
context: {
hasEnv: !!ctx.env,
hasRuntime: !!ctx.runtime,
envKeys: ctx.env ? Object.keys(ctx.env) : [],
runtimeEnvKeys: ctx.runtime?.env ? Object.keys(ctx.runtime.env) : []
}
}), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
try {
// Get current view count
const { results } = await db
.prepare('SELECT views FROM pageviews WHERE slug = ?')
.bind(slug)
.all();
const views = results.length > 0 ? results[0].views : 0;
return new Response(JSON.stringify({ views }), {
status: 200,
headers: {
'Content-Type': 'application/json',
},
});
} catch (error) {
console.error('Error getting page views:', error);
return new Response(
JSON.stringify({
error: 'Failed to get page views',
details: error instanceof Error ? error.message : String(error)
}), {
status: 500,
headers: {
'Content-Type': 'application/json',
},
});
}
};
export const POST: APIRoute = async ({ params, locals, request }) => {
const slug = params.slug;
if (!slug) {
return new Response(JSON.stringify({ error: 'Slug is required' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
});
}
// Access runtime environment through context
const ctx = locals as any;
const env = ctx.env || ctx.runtime?.env;
console.log('Context:', {
hasEnv: !!ctx.env,
hasRuntime: !!ctx.runtime,
envKeys: ctx.env ? Object.keys(ctx.env) : [],
runtimeEnvKeys: ctx.runtime?.env ? Object.keys(ctx.runtime.env) : []
});
const db = env?.DB;
if (!db) {
console.error('D1 database not available');
return new Response(
JSON.stringify({
error: 'Database not configured',
context: {
hasEnv: !!ctx.env,
hasRuntime: !!ctx.runtime,
envKeys: ctx.env ? Object.keys(ctx.env) : [],
runtimeEnvKeys: ctx.runtime?.env ? Object.keys(ctx.runtime.env) : []
}
}), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
try {
// Insert or update view count
await db
.prepare(
`INSERT INTO pageviews (slug, views)
VALUES (?, 1)
ON CONFLICT(slug)
DO UPDATE SET views = views + 1,
updated_at = CURRENT_TIMESTAMP`
)
.bind(slug)
.run();
// Get updated view count
const { results } = await db
.prepare('SELECT views FROM pageviews WHERE slug = ?')
.bind(slug)
.all();
return new Response(JSON.stringify({ views: results[0].views }), {
status: 200,
headers: {
'Content-Type': 'application/json',
},
});
} catch (error) {
console.error('Error updating page views:', error);
return new Response(
JSON.stringify({
error: 'Failed to update page views',
details: error instanceof Error ? error.message : String(error)
}), {
status: 500,
headers: {
'Content-Type': 'application/json',
},
});
}
};