aboutsummaryrefslogtreecommitdiffstats
path: root/middleware/src/middleware.ts
blob: 78aa3f4d3fbfe6a0c5cec028304911dba2de7bee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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()
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage