34 lines
1.0 KiB
TypeScript
34 lines
1.0 KiB
TypeScript
import { createReadStream } from 'node:fs'
|
|
import { extname } from 'node:path'
|
|
import { sendStream } from 'h3'
|
|
import { resolveExistingUploadThumbnailPath, UPLOAD_THUMBNAIL_PREFIX } from '~/server/utils/upload'
|
|
|
|
const MIME_TYPES: Record<string, string> = {
|
|
'.jpg': 'image/jpeg',
|
|
'.jpeg': 'image/jpeg',
|
|
'.png': 'image/png',
|
|
'.gif': 'image/gif',
|
|
'.webp': 'image/webp',
|
|
'.avif': 'image/avif',
|
|
}
|
|
|
|
export default defineEventHandler((event) => {
|
|
const path = getRouterParam(event, 'path')
|
|
if (!path || path.includes('..')) {
|
|
throw createError({ statusCode: 404, statusMessage: 'Not Found' })
|
|
}
|
|
|
|
const filePath = resolveExistingUploadThumbnailPath(`${UPLOAD_THUMBNAIL_PREFIX}${path}`)
|
|
if (!filePath) {
|
|
throw createError({ statusCode: 404, statusMessage: 'Not Found' })
|
|
}
|
|
|
|
const contentType = MIME_TYPES[extname(path).toLowerCase()]
|
|
if (contentType) {
|
|
setHeader(event, 'Content-Type', contentType)
|
|
}
|
|
setHeader(event, 'Cache-Control', 'public, max-age=31536000, immutable')
|
|
|
|
return sendStream(event, createReadStream(filePath))
|
|
})
|