fix(images) : retry failed CDN images through Cloudflare resizing
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
"use client";
|
||||
|
||||
import NextImage, { type ImageProps } from "next/image";
|
||||
import { useState } from "react";
|
||||
|
||||
const CDN_ORIGIN = "https://buzz-cdn.astrxl.dev";
|
||||
|
||||
export default function ResilientImage({ src, unoptimized, onError, ...props }: ImageProps) {
|
||||
const [fallback, setFallback] = useState<{ source: string; url: string } | null>(null);
|
||||
const fallbackUrl = typeof src === "string" && fallback?.source === src ? fallback.url : null;
|
||||
|
||||
return (
|
||||
<NextImage
|
||||
{...props}
|
||||
src={fallbackUrl ?? src}
|
||||
unoptimized={unoptimized || Boolean(fallbackUrl)}
|
||||
onError={(event) => {
|
||||
if (!fallbackUrl && typeof src === "string" && src.startsWith(`${CDN_ORIGIN}/`)) {
|
||||
const source = new URL(src);
|
||||
if (!source.pathname.startsWith("/cdn-cgi/image/")) {
|
||||
const optimized = new URL(event.currentTarget.currentSrc);
|
||||
const width = Number(optimized.searchParams.get("w")) || 1080;
|
||||
const quality = Number(optimized.searchParams.get("q")) || 75;
|
||||
setFallback({
|
||||
source: src,
|
||||
url: `${CDN_ORIGIN}/cdn-cgi/image/width=${width},quality=${quality},format=auto${source.pathname}${source.search}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
onError?.(event);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user