정보게시판
ip 조회하여 뷰업데이트
116
0
// 1. 먼저 Supabase에 새 테이블을 생성합니다. SQL 편집기에서 다음 쿼리를 실행하세요:
/*
CREATE TABLE post_views (
id BIGSERIAL PRIMARY KEY,
post_id BIGINT REFERENCES posts(id),
ip_address TEXT,
viewed_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
UNIQUE(post_id, ip_address)
);
*/
// 2. 서버 액션 파일 (예: /actions/postActions.ts)에 다음 코드를 추가합니다:
'use server'
import { createClient } from '@/lib/supabase/supabaseServer'
import { revalidatePath } from 'next/cache'
import { headers } from 'next/headers'
export async function incrementViewCount(postId: string) {
const supabase = createClient()
// 클라이언트 IP 주소 가져오기
const forwardedFor = headers().get('x-forwarded-for')
const ip = forwardedFor ? forwardedFor.split(',')[0] : 'Unknown'
// 이미 해당 IP에서 조회한 기록이 있는지 확인
const { data: existingView, error: viewError } = await supabase
.from('post_views')
.select()
.eq('post_id', postId)
.eq('ip_address', ip)
.maybeSingle()
if (viewError) {
console.error('Error checking existing view:', viewError)
throw new Error('Failed to check existing view')
}
// 이미 조회한 기록이 없으면 새로운 조회 기록 추가 및 조회수 증가
if (!existingView) {
const { error: insertError } = await supabase
.from('post_views')
.insert({ post_id: postId, ip_address: ip })
if (insertError) {
console.error('Error inserting new view:', insertError)
throw new Error('Failed to insert new view')
}
// 조회수 증가
const { data, error: updateError } = await supabase
.from('posts')
.update({ views: supabase.rpc('increment_view_count', { post_id: postId }) })
.eq('id', postId)
.select()
if (updateError) {
console.error('Error incrementing view count:', updateError)
throw new Error('Failed to increment view count')
}
revalidatePath(`/posts/[slug]/[id]`)
return data[0]
}
// 이미 조회한 기록이 있으면 기존 게시물 데이터 반환
const { data: currentPost, error: fetchError } = await supabase
.from('posts')
.select()
.eq('id', postId)
.single()
if (fetchError) {
console.error('Error fetching current post:', fetchError)
throw new Error('Failed to fetch current post')
}
return currentPost
}
// 3. Supabase SQL 편집기에서 다음 함수를 생성합니다:
/*
create or replace function increment_view_count(post_id bigint)
returns integer as $$
declare
new_views integer;
begin
update posts
set views = views + 1
where id = post_id
returning views into new_views;
return new_views;
end;
$$ language plpgsql;
*/
// 4. 페이지 컴포넌트 (예: /app/posts/[slug]/[id]/page.tsx)에서 이 함수를 사용합니다:
import { incrementViewCount } from '@/actions/postActions';
// ... 기존 코드 ...
async function getPostDetail(slug: string, id: string) {
// ... 기존 코드 ...
if (post) {
// Increment view count
const updatedPost = await incrementViewCount(id);
return { ...updatedPost, categoryName };
} else {
return null;
}
}
추후 어느정도 작업 후 예정