feat: revalidate webhook endpoint with tests
This commit is contained in:
@@ -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}`],
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user