mirror of
https://github.com/walkxcode/dashboard-icons.git
synced 2025-11-18 17:47:30 +01:00
VIbe-code some optimizations
This commit is contained in:
@@ -135,9 +135,7 @@ export default async function Image({ params }: { params: Promise<{ icon: string
|
||||
}
|
||||
}
|
||||
|
||||
const iconUrl = iconDataBuffer
|
||||
? `data:image/png;base64,${iconDataBuffer.toString("base64")}`
|
||||
: `https://placehold.co/600x400?text=${formattedIconName}`
|
||||
const iconUrl = iconDataBuffer ? `data:image/png;base64,${iconDataBuffer.toString("base64")}` : null
|
||||
|
||||
return new ImageResponse(
|
||||
<div
|
||||
@@ -242,18 +240,39 @@ export default async function Image({ params }: { params: Promise<{ icon: string
|
||||
zIndex: 0,
|
||||
}}
|
||||
/>
|
||||
<img
|
||||
src={iconUrl}
|
||||
alt={formattedIconName}
|
||||
width={260}
|
||||
height={260}
|
||||
style={{
|
||||
objectFit: "contain",
|
||||
position: "relative",
|
||||
zIndex: 1,
|
||||
filter: "drop-shadow(0 10px 15px rgba(0, 0, 0, 0.1))",
|
||||
}}
|
||||
/>
|
||||
{iconUrl ? (
|
||||
<img
|
||||
src={iconUrl}
|
||||
alt={formattedIconName}
|
||||
width={260}
|
||||
height={260}
|
||||
style={{
|
||||
objectFit: "contain",
|
||||
position: "relative",
|
||||
zIndex: 1,
|
||||
filter: "drop-shadow(0 10px 15px rgba(0, 0, 0, 0.1))",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
width: 260,
|
||||
height: 260,
|
||||
position: "relative",
|
||||
zIndex: 1,
|
||||
fontSize: 48,
|
||||
fontWeight: 700,
|
||||
color: "#94a3b8",
|
||||
textAlign: "center",
|
||||
wordBreak: "break-word",
|
||||
}}
|
||||
>
|
||||
{formattedIconName}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { join } from "node:path"
|
||||
import { ImageResponse } from "next/og"
|
||||
import { getAllIcons } from "@/lib/api"
|
||||
import { preloadAllIcons, readIconFile } from "@/lib/icon-cache"
|
||||
|
||||
export const revalidate = false
|
||||
|
||||
export async function generateStaticParams() {
|
||||
const iconsData = await getAllIcons()
|
||||
if (process.env.CI_MODE === "false") {
|
||||
// This is meant to speed up the build process in local development
|
||||
return Object.keys(iconsData)
|
||||
.slice(0, 5)
|
||||
.map((icon) => ({
|
||||
@@ -49,27 +47,18 @@ export default async function Image({ params }: { params: Promise<{ icon: string
|
||||
)
|
||||
}
|
||||
|
||||
await preloadAllIcons()
|
||||
|
||||
const iconsData = await getAllIcons()
|
||||
const totalIcons = Object.keys(iconsData).length
|
||||
const index = Object.keys(iconsData).indexOf(icon)
|
||||
|
||||
// Format the icon name for display
|
||||
const formattedIconName = icon
|
||||
.split("-")
|
||||
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(" ")
|
||||
|
||||
// Read the icon file from local filesystem
|
||||
let iconData: Buffer | null = null
|
||||
try {
|
||||
const iconPath = join(process.cwd(), `../png/${icon}.png`)
|
||||
console.log(`Generating opengraph image for ${icon} (${index + 1} / ${totalIcons}) from path ${iconPath}`)
|
||||
iconData = await readFile(iconPath)
|
||||
} catch (_error) {
|
||||
console.error(`Icon ${icon} was not found locally`)
|
||||
}
|
||||
|
||||
// Convert the image data to a data URL or use placeholder
|
||||
const iconData = await readIconFile(icon)
|
||||
const iconUrl = iconData ? `data:image/png;base64,${iconData.toString("base64")}` : null
|
||||
|
||||
return new ImageResponse(
|
||||
@@ -154,18 +143,39 @@ export default async function Image({ params }: { params: Promise<{ icon: string
|
||||
zIndex: 0,
|
||||
}}
|
||||
/>
|
||||
<img
|
||||
src={iconUrl || `https://placehold.co/600x400?text=${formattedIconName}`}
|
||||
alt={formattedIconName}
|
||||
width={260}
|
||||
height={260}
|
||||
style={{
|
||||
objectFit: "contain",
|
||||
position: "relative",
|
||||
zIndex: 1,
|
||||
filter: "drop-shadow(0 10px 15px rgba(0, 0, 0, 0.1))",
|
||||
}}
|
||||
/>
|
||||
{iconUrl ? (
|
||||
<img
|
||||
src={iconUrl}
|
||||
alt={formattedIconName}
|
||||
width={260}
|
||||
height={260}
|
||||
style={{
|
||||
objectFit: "contain",
|
||||
position: "relative",
|
||||
zIndex: 1,
|
||||
filter: "drop-shadow(0 10px 15px rgba(0, 0, 0, 0.1))",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
width: 260,
|
||||
height: 260,
|
||||
position: "relative",
|
||||
zIndex: 1,
|
||||
fontSize: 48,
|
||||
fontWeight: 700,
|
||||
color: "#94a3b8",
|
||||
textAlign: "center",
|
||||
wordBreak: "break-word",
|
||||
}}
|
||||
>
|
||||
{formattedIconName}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Text content */}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { unstable_cache } from "next/cache"
|
||||
import { cache } from "react"
|
||||
import { METADATA_URL } from "@/constants"
|
||||
import { ApiError } from "@/lib/errors"
|
||||
import type { AuthorData, IconFile, IconWithName } from "@/types/icons"
|
||||
|
||||
/**
|
||||
* Fetches all icon data from the metadata.json file
|
||||
* Uses fetch with revalidate for caching
|
||||
* Raw fetch function for icon data (without caching)
|
||||
*/
|
||||
export async function getAllIcons(): Promise<IconFile> {
|
||||
async function fetchAllIconsRaw(): Promise<IconFile> {
|
||||
try {
|
||||
const response = await fetch(METADATA_URL)
|
||||
const response = await fetch(METADATA_URL, {
|
||||
next: { revalidate: 3600 },
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ApiError(`Failed to fetch icons: ${response.statusText}`, response.status)
|
||||
@@ -25,6 +27,24 @@ export async function getAllIcons(): Promise<IconFile> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached version using unstable_cache for build-time caching
|
||||
* Revalidates every hour (3600 seconds)
|
||||
*/
|
||||
const getAllIconsCached = unstable_cache(async () => fetchAllIconsRaw(), ["all-icons"], {
|
||||
revalidate: 3600,
|
||||
tags: ["icons"],
|
||||
})
|
||||
|
||||
/**
|
||||
* Fetches all icon data from the metadata.json file
|
||||
* Uses React cache() for request-level memoization and unstable_cache for build-level caching
|
||||
* This prevents duplicate fetches within the same request and across builds
|
||||
*/
|
||||
export const getAllIcons = cache(async (): Promise<IconFile> => {
|
||||
return getAllIconsCached()
|
||||
})
|
||||
|
||||
/**
|
||||
* Gets a list of all icon names.
|
||||
*/
|
||||
@@ -122,7 +142,7 @@ async function fetchAuthorData(authorId: number) {
|
||||
}
|
||||
}
|
||||
|
||||
const authorDataCache: Record<number, AuthorData> = {};
|
||||
const authorDataCache: Record<number, AuthorData> = {}
|
||||
|
||||
/**
|
||||
* Cached version of fetchAuthorData
|
||||
@@ -135,12 +155,12 @@ const authorDataCache: Record<number, AuthorData> = {};
|
||||
*/
|
||||
export async function getAuthorData(authorId: number): Promise<AuthorData> {
|
||||
if (authorDataCache[authorId]) {
|
||||
return authorDataCache[authorId];
|
||||
return authorDataCache[authorId]
|
||||
}
|
||||
|
||||
const data = await fetchAuthorData(authorId);
|
||||
authorDataCache[authorId] = data;
|
||||
return data;
|
||||
const data = await fetchAuthorData(authorId)
|
||||
authorDataCache[authorId] = data
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -10,6 +10,3 @@ export class ApiError extends Error {
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
76
web/src/lib/icon-cache.ts
Normal file
76
web/src/lib/icon-cache.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { join } from "node:path"
|
||||
import { cache } from "react"
|
||||
import { getAllIcons } from "./api"
|
||||
|
||||
/**
|
||||
* In-memory cache for icon files during build/request
|
||||
* This persists across multiple calls within the same build process
|
||||
*/
|
||||
const iconFileCache = new Map<string, Buffer | null>()
|
||||
let preloadPromise: Promise<void> | null = null
|
||||
let isPreloaded = false
|
||||
|
||||
/**
|
||||
* Preloads all icon files into memory
|
||||
* This should be called once at the start of the build process
|
||||
*/
|
||||
export async function preloadAllIcons(): Promise<void> {
|
||||
if (isPreloaded || preloadPromise) {
|
||||
return preloadPromise || Promise.resolve()
|
||||
}
|
||||
|
||||
preloadPromise = (async () => {
|
||||
const startTime = Date.now()
|
||||
const iconsData = await getAllIcons()
|
||||
const iconNames = Object.keys(iconsData)
|
||||
const pngDir = join(process.cwd(), `../png`)
|
||||
|
||||
console.log(`[Icon Cache] Preloading ${iconNames.length} icons into memory...`)
|
||||
|
||||
const loadPromises = iconNames.map(async (iconName) => {
|
||||
if (iconFileCache.has(iconName)) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const iconPath = join(pngDir, `${iconName}.png`)
|
||||
const buffer = await readFile(iconPath)
|
||||
iconFileCache.set(iconName, buffer)
|
||||
} catch (_error) {
|
||||
iconFileCache.set(iconName, null)
|
||||
}
|
||||
})
|
||||
|
||||
await Promise.all(loadPromises)
|
||||
const duration = Date.now() - startTime
|
||||
const loadedCount = Array.from(iconFileCache.values()).filter((v) => v !== null).length
|
||||
console.log(
|
||||
`[Icon Cache] Preloaded ${loadedCount}/${iconNames.length} icons in ${duration}ms (${(loadedCount / duration).toFixed(2)} icons/ms)`,
|
||||
)
|
||||
isPreloaded = true
|
||||
})()
|
||||
|
||||
return preloadPromise
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads an icon PNG file from the filesystem
|
||||
* Uses React cache() for request-level memoization
|
||||
* Uses in-memory Map for build-level caching
|
||||
* If preloaded, returns immediately from cache
|
||||
*/
|
||||
export const readIconFile = cache(async (iconName: string): Promise<Buffer | null> => {
|
||||
if (iconFileCache.has(iconName)) {
|
||||
return iconFileCache.get(iconName)!
|
||||
}
|
||||
|
||||
try {
|
||||
const iconPath = join(process.cwd(), `../png/${iconName}.png`)
|
||||
const buffer = await readFile(iconPath)
|
||||
iconFileCache.set(iconName, buffer)
|
||||
return buffer
|
||||
} catch (_error) {
|
||||
iconFileCache.set(iconName, null)
|
||||
return null
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user