|
| 1 | +import { invariantResponse } from '@epic-web/invariant' |
| 2 | +import { getImgResponse } from 'openimg/node' |
| 3 | +import { getDomainUrl } from '#app/utils/misc.tsx' |
| 4 | +import { getSignedGetRequestInfo } from '#app/utils/storage.server.ts' |
| 5 | +import { type Route } from './+types/images' |
| 6 | + |
| 7 | +export async function loader({ request }: Route.LoaderArgs) { |
| 8 | + const url = new URL(request.url) |
| 9 | + const searchParams = url.searchParams |
| 10 | + |
| 11 | + const headers = new Headers() |
| 12 | + headers.set('Cache-Control', 'public, max-age=31536000, immutable') |
| 13 | + |
| 14 | + const objectKey = searchParams.get('objectKey') |
| 15 | + |
| 16 | + return getImgResponse(request, { |
| 17 | + headers, |
| 18 | + allowlistedOrigins: [ |
| 19 | + getDomainUrl(request), |
| 20 | + process.env.AWS_ENDPOINT_URL_S3, |
| 21 | + ].filter(Boolean), |
| 22 | + cacheFolder: |
| 23 | + process.env.NODE_ENV === 'production' |
| 24 | + ? '/data/images' |
| 25 | + : './tests/fixtures/openimg', |
| 26 | + getImgSource: () => { |
| 27 | + if (objectKey) { |
| 28 | + const { url: signedUrl, headers: signedHeaders } = |
| 29 | + getSignedGetRequestInfo(objectKey) |
| 30 | + return { |
| 31 | + type: 'fetch', |
| 32 | + url: signedUrl, |
| 33 | + headers: signedHeaders, |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + const src = searchParams.get('src') |
| 38 | + invariantResponse(src, 'src query parameter is required', { status: 400 }) |
| 39 | + |
| 40 | + if (URL.canParse(src)) { |
| 41 | + // Fetch image from external URL; will be matched against allowlist |
| 42 | + return { |
| 43 | + type: 'fetch', |
| 44 | + url: src, |
| 45 | + } |
| 46 | + } |
| 47 | + // Retrieve image from filesystem (public folder) |
| 48 | + if (src.startsWith('/assets')) { |
| 49 | + // Files managed by Vite |
| 50 | + return { |
| 51 | + type: 'fs', |
| 52 | + path: '.' + src, |
| 53 | + } |
| 54 | + } |
| 55 | + // Fallback to files in public folder |
| 56 | + return { |
| 57 | + type: 'fs', |
| 58 | + path: './public' + src, |
| 59 | + } |
| 60 | + }, |
| 61 | + }) |
| 62 | +} |
0 commit comments