feat: revalidate webhook endpoint with tests

This commit is contained in:
achmad
2026-05-28 22:33:25 +07:00
parent e748725522
commit e45faa201f
2 changed files with 138 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
import { revalidatePath } from 'next/cache'
import { NextRequest, NextResponse } from 'next/server'
import { createDirectus, rest, staticToken, readItem } from '@directus/sdk'
export async function POST(req: NextRequest) {
const body = await req.json()
if (body.secret !== process.env.REVALIDATE_SECRET) {
return NextResponse.json({ error: 'Invalid secret' }, { status: 401 })
}
if (body.type === 'homepage') {
revalidatePath('/')
return NextResponse.json({ revalidated: true, path: '/' })
}
const { article_id } = body
if (!article_id) {
return NextResponse.json({ error: 'Missing article_id' }, { status: 400 })
}
const directus = createDirectus(process.env.DIRECTUS_URL!)
.with(staticToken(process.env.DIRECTUS_TOKEN!))
.with(rest())
const article = (await directus.request(
readItem('articles', article_id, {
fields: ['slug', 'category.slug'],
})
)) as { slug: string; category: { slug: string } } | null
if (!article) {
return NextResponse.json({ error: 'Article not found' }, { status: 404 })
}
const categorySlug = article.category.slug
const { slug } = article
revalidatePath('/')
revalidatePath(`/${categorySlug}`)
revalidatePath(`/${categorySlug}/${slug}`)
return NextResponse.json({
revalidated: true,
paths: ['/', `/${categorySlug}`, `/${categorySlug}/${slug}`],
})
}