Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions app/api/blog/[slug]/views/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';

export async function POST(req: NextRequest) {
const supabase = await createClient();
// Extract slug from the URL
const url = req.nextUrl || new URL(req.url);
const match = url.pathname.match(/\/blog\/([^/]+)\/views/);
const slug = match ? decodeURIComponent(match[1]) : null;

if (!slug) {
return NextResponse.json({ error: 'Missing slug' }, { status: 400 });
}

// Get current views
const { data: current, error: fetchError } = await supabase
.from('blogs')
.select('views')
.eq('slug', slug)
.single();

if (fetchError || !current) {
return NextResponse.json({ error: fetchError?.message || 'Blog not found' }, { status: 500 });
}

// increment views
const { data, error } = await supabase
.from('blogs')
.update({ views: (current.views || 0) + 1 })
.eq('slug', slug)
.select('views')
.single();

if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}

return NextResponse.json({ views: data.views });
}

export async function GET(req: NextRequest) {
const supabase = await createClient();
// extract slug from the url
const url = req.nextUrl || new URL(req.url);
const match = url.pathname.match(/\/blog\/([^/]+)\/views/);
const slug = match ? decodeURIComponent(match[1]) : null;

if (!slug) {
return NextResponse.json({ error: 'Missing slug' }, { status: 400 });
}

const { data, error } = await supabase
.from('blogs')
.select('views')
.eq('slug', slug)
.single();

if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}

return NextResponse.json({ views: data.views });
}
41 changes: 40 additions & 1 deletion app/blog/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export default function BlogPostPage() {
const [fetchError, setFetchError] = useState<string | null>(null)
const [likeCount, setLikeCount] = useState(0);
const [likedByUser, setLikedByUser] = useState(false);
const [views, setViews] = useState<number>(0);
const params = useParams()

const slug = params?.slug as string
Expand Down Expand Up @@ -134,6 +135,44 @@ export default function BlogPostPage() {
if (slug) fetchLikeData();
}, [slug]);

useEffect(() => {
if (!slug) return;
const viewedKey = `viewed_${slug}`;
if (!localStorage.getItem(viewedKey)) {
// Increment views only if not viewed in this session
fetch(`/api/blog/${slug}/views`, { method: 'POST' })
.then(res => res.json())
.then(data => {
if (typeof data.views === 'number') setViews(data.views);
});
localStorage.setItem(viewedKey, 'true');
} else {
// Just fetch the current count
fetch(`/api/blog/${slug}/views`)
.then(res => res.json())
.then(data => {
if (typeof data.views === 'number') setViews(data.views);
});
}
// Subscribe to realtime updates
const supabase = createClient();
const channel = supabase.channel('blogs-views')
.on('postgres_changes', {
event: 'UPDATE',
schema: 'public',
table: 'blogs',
filter: `slug=eq.${slug}`,
}, (payload) => {
if (payload.new && typeof payload.new.views === 'number') {
setViews(payload.new.views);
}
})
.subscribe();
return () => {
supabase.removeChannel(channel);
};
}, [slug]);

const getCategoryColor = (category: string) => {
switch (category) {
case "Frontend":
Expand Down Expand Up @@ -274,7 +313,7 @@ export default function BlogPostPage() {
</div>
<div className="flex items-center space-x-2 bg-background/80 backdrop-blur-sm px-3 py-2 rounded-full">
<Eye className="h-4 w-4" />
<span>{post?.views} views</span>
<span>{views} views</span>
</div>
<div className="flex items-center space-x-2 bg-background/80 backdrop-blur-sm px-3 py-2 rounded-full">
<Heart className="h-4 w-4" />
Expand Down