51 lines
1.3 KiB
TypeScript
51 lines
1.3 KiB
TypeScript
import { api } from "@otunes/convex/_generated/api"
|
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
|
import sharp from "sharp"
|
|
import { fetchConvexStorageFile, getConvexClient } from "@/lib/convex-server"
|
|
|
|
const AVATAR_SIZE = 256
|
|
|
|
/**
|
|
* Serves a profile photo from Convex storage, downscaled. URLs carry the
|
|
* storage id (`?v=`), so a new photo gets a new URL and responses can be
|
|
* cached for good.
|
|
*/
|
|
export async function GET(
|
|
_request: Request,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
const { id } = await params
|
|
try {
|
|
const storageUrl = await getConvexClient().query(
|
|
api.users.getProfileImageUrl,
|
|
{ userId: id as Id<"users"> }
|
|
)
|
|
if (!storageUrl) {
|
|
return new Response("Not found", { status: 404 })
|
|
}
|
|
|
|
const image = await fetchConvexStorageFile(storageUrl)
|
|
if (!image) {
|
|
return new Response("Not found", { status: 404 })
|
|
}
|
|
|
|
const data = await sharp(image)
|
|
.rotate()
|
|
.resize(AVATAR_SIZE, AVATAR_SIZE, {
|
|
fit: "cover",
|
|
withoutEnlargement: true,
|
|
})
|
|
.webp({ quality: 85 })
|
|
.toBuffer()
|
|
|
|
return new Response(new Uint8Array(data), {
|
|
headers: {
|
|
"Content-Type": "image/webp",
|
|
"Cache-Control": "public, max-age=31536000, immutable",
|
|
},
|
|
})
|
|
} catch {
|
|
return new Response("Not found", { status: 404 })
|
|
}
|
|
}
|