diff options
| author | Pinapelz <yukais@pinapelz.com> | 2025-06-30 23:14:14 -0700 |
|---|---|---|
| committer | Pinapelz <yukais@pinapelz.com> | 2025-06-30 23:14:14 -0700 |
| commit | 7a0a37568a0c5726d25ebf807d8d05c0e4faa74c (patch) | |
| tree | 718972faa1e45656861249c01c850a9adb697173 /middleware/src/middleware.ts | |
| parent | ce903edb37d9c11ff1e983fbf1015cd95af31140 (diff) | |
add opengraph middleware
Diffstat (limited to 'middleware/src/middleware.ts')
| -rw-r--r-- | middleware/src/middleware.ts | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/middleware/src/middleware.ts b/middleware/src/middleware.ts new file mode 100644 index 0000000..78aa3f4 --- /dev/null +++ b/middleware/src/middleware.ts @@ -0,0 +1,42 @@ +import { NextRequest, NextResponse } from 'next/server' + +export async function middleware(request: NextRequest) { + const url = request.nextUrl + const pathname = url.pathname + if(pathname.startsWith("/_") || pathname.startsWith("/favicon")){ + return; + } + const searchParams = url.searchParams + const gameName = pathname.split('/')[1] || 'news' + const postId = searchParams.get('post') + const apiUrlBase = process.env.NEXT_PUBLIC_API_URL + if (postId) { + try { + console.log(`Game: ${gameName}, Post ID: ${postId}`) + const newsDataUrl = apiUrlBase+"/"+gameName+"_news.json"; + const res = await fetch(newsDataUrl) + if (res.ok) { + const data = await res.json() + const newsPosts = data["news_posts"]; + const matchingPost = newsPosts.find((news: any) => { + const contentHash = news.content.split('').reduce((hash: number, char: string) => ((hash << 5) + hash) + char.charCodeAt(0), 5381) >>> 0; + const newsId = `${news.identifier}-${news.timestamp}-${contentHash.toString(16)}-${news.headline}`; + return newsId === postId; + }); + const response = NextResponse.next() + if(matchingPost.headline){ + response.headers.set('x-post-headline', encodeURIComponent(matchingPost.headline)); + } + if(matchingPost.images && matchingPost.images.length >= 1 ){ + response.headers.set('x-post-heroImage', matchingPost.images[0].image); + } + response.headers.set('x-post-content', encodeURIComponent(matchingPost.content)); + response.headers.set('x-post-timestamp', matchingPost.timestamp); + return response + } + } catch (e) { + console.warn('Failed to fetch post metadata:', e) + } + } + return NextResponse.next() +} |
