|
| 1 | +import type { NextRequest } from 'next/server'; |
| 2 | + |
| 3 | +import { graphqlDirect } from '@/lib/graphql/graphql-direct'; |
| 4 | +import { AvatarByLoginDocument } from '@/types/generated/graphql'; |
| 5 | + |
| 6 | +type Props = { params: Promise<{ login: string }> }; |
| 7 | + |
| 8 | +export async function GET(req: NextRequest, { params }: Props) { |
| 9 | + const { login } = await params; |
| 10 | + |
| 11 | + const { user } = await graphqlDirect(AvatarByLoginDocument, { login }); |
| 12 | + |
| 13 | + if (!user?.avatarUrl) { |
| 14 | + return new Response('User not found', { status: 404 }); |
| 15 | + } |
| 16 | + |
| 17 | + const src = user.avatarUrl; |
| 18 | + |
| 19 | + // Forward validators for 304 support |
| 20 | + const etag = req.headers.get('if-none-match') ?? undefined; |
| 21 | + const ims = req.headers.get('if-modified-since') ?? undefined; |
| 22 | + |
| 23 | + const upstream = await fetch(src, { |
| 24 | + headers: { |
| 25 | + ...(etag ? { 'if-none-match': etag } : {}), |
| 26 | + ...(ims ? { 'if-modified-since': ims } : {}), |
| 27 | + // Optional: set Accept for smaller formats if GH honors it (not guaranteed) |
| 28 | + Accept: req.headers.get('accept') ?? 'image/*', |
| 29 | + // Never forward arbitrary user-provided headers |
| 30 | + }, |
| 31 | + // Let your platform/CDN cache it: |
| 32 | + next: { revalidate: 60 * 60 * 24 }, // 1 day (app-level hint) |
| 33 | + }); |
| 34 | + |
| 35 | + // Pass through 304 to leverage browser/CDN cache |
| 36 | + if (upstream.status === 304) { |
| 37 | + return new Response(null, { |
| 38 | + status: 304, |
| 39 | + headers: { |
| 40 | + 'Cache-Control': 'public, max-age=0, s-maxage=604800, stale-while-revalidate=86400', |
| 41 | + }, |
| 42 | + }); |
| 43 | + } |
| 44 | + |
| 45 | + if (!upstream.ok) { |
| 46 | + // if GitHub itself returns 404 → bubble it up |
| 47 | + return new Response('Avatar not found', { status: 404 }); |
| 48 | + } |
| 49 | + |
| 50 | + // Stream the body; copy key headers safely |
| 51 | + const resHeaders = new Headers(); |
| 52 | + const ct = upstream.headers.get('content-type'); |
| 53 | + if (ct) resHeaders.set('Content-Type', ct); |
| 54 | + |
| 55 | + const lm = upstream.headers.get('last-modified'); |
| 56 | + if (lm) resHeaders.set('Last-Modified', lm); |
| 57 | + |
| 58 | + const et = upstream.headers.get('etag'); |
| 59 | + if (et) resHeaders.set('ETag', et); |
| 60 | + |
| 61 | + // Your cache policy |
| 62 | + resHeaders.set('Cache-Control', 'public, max-age=0, s-maxage=604800, stale-while-revalidate=86400'); |
| 63 | + // Optional CSP tightening: |
| 64 | + // resHeaders.set("Cross-Origin-Resource-Policy", "same-site"); |
| 65 | + |
| 66 | + return new Response(upstream.body, { |
| 67 | + status: upstream.status, |
| 68 | + headers: resHeaders, |
| 69 | + }); |
| 70 | +} |
0 commit comments