route.ts

1import { NextResponse } from 'next/server'
2import { getContent, sortContentByDate } from '@/lib/content'
3
4export async function GET(request: Request) {
5	const { searchParams } = new URL(request.url)
6	const year = searchParams.get('year')
7	const month = searchParams.get('month')
8	const day = searchParams.get('day')
9	const slug = searchParams.get('slug')
10
11	try {
12		const posts = sortContentByDate(getContent('blog'))
13
14		if (slug) {
15			const post = posts.find((post) => post.slug === slug)
16			if (!post)
17				return NextResponse.json({ error: 'Post not found' }, { status: 404 })
18			return NextResponse.json(post)
19		}
20
21		const filteredPosts = posts.filter((post) => {
22			const date = new Date(post.metadata.date)
23
24			if (year && date.getFullYear() !== parseInt(year)) return false
25			if (month && date.getMonth() + 1 !== parseInt(month)) return false
26			if (day && date.getDate() !== parseInt(day)) return false
27
28			return true
29		})
30
31		return NextResponse.json(filteredPosts)
32	} catch (error) {
33		console.error('Error fetching blog posts:', error)
34		return NextResponse.json(
35			{ error: 'Failed to fetch blog posts' },
36			{ status: 500 },
37		)
38	}
39}
40