|
| 1 | +import { Hono } from "hono"; |
| 2 | +import { s3 } from "../configs"; |
| 3 | +import { |
| 4 | + storagePresignBodyValidator, |
| 5 | + storageReadBodyValidator, |
| 6 | +} from "../validators/storage.validator"; |
| 7 | +import slugify from "slugify"; |
| 8 | + |
| 9 | +const ALLOWED_TYPES = [ |
| 10 | + "image/jpeg", |
| 11 | + "image/png", |
| 12 | + "image/webp", |
| 13 | + "image/heic", |
| 14 | + "image/heif", |
| 15 | +]; |
| 16 | + |
| 17 | +export const storageRoutes = new Hono(); |
| 18 | + |
| 19 | +// POST /api/storage - Get presigned URL for upload |
| 20 | +storageRoutes.post("/", storagePresignBodyValidator, async (c) => { |
| 21 | + const { fileName } = await c.req.json(); |
| 22 | + |
| 23 | + const ext = fileName.substring(fileName.lastIndexOf(".")); |
| 24 | + const nameWithoutExt = fileName.substring(0, fileName.lastIndexOf(".")); |
| 25 | + |
| 26 | + const extToType: Record<string, string> = { |
| 27 | + ".jpg": "image/jpeg", |
| 28 | + ".jpeg": "image/jpeg", |
| 29 | + ".png": "image/png", |
| 30 | + ".webp": "image/webp", |
| 31 | + ".heic": "image/heic", |
| 32 | + ".heif": "image/heif", |
| 33 | + }; |
| 34 | + |
| 35 | + const contentType = extToType[ext] ?? ""; |
| 36 | + |
| 37 | + if (!ALLOWED_TYPES.includes(contentType)) { |
| 38 | + return c.json({ error: "Invalid file type" }, 400); |
| 39 | + } |
| 40 | + |
| 41 | + const sanitizedFileName = slugify(nameWithoutExt, { |
| 42 | + lower: true, |
| 43 | + strict: true, |
| 44 | + trim: true, |
| 45 | + }).substring(0, 100); |
| 46 | + |
| 47 | + const uuid = crypto.randomUUID(); |
| 48 | + const key = `uploads/${sanitizedFileName}-${uuid}${ext}`; |
| 49 | + |
| 50 | + const uploadUrl = s3.presign(key, { |
| 51 | + expiresIn: 60 * 15, // 15 minutes |
| 52 | + method: "PUT", |
| 53 | + type: contentType, |
| 54 | + }); |
| 55 | + |
| 56 | + return c.json({ url: uploadUrl, key, contentType }); |
| 57 | +}); |
| 58 | + |
| 59 | +// GET /api/storage - Get presigned URL for reading |
| 60 | +storageRoutes.get("/", storageReadBodyValidator, async (c) => { |
| 61 | + const { key } = c.req.query(); |
| 62 | + |
| 63 | + const readUrl = s3.presign(key, { |
| 64 | + method: "GET", |
| 65 | + expiresIn: 60 * 60, // 1 hour |
| 66 | + }); |
| 67 | + |
| 68 | + return c.json({ url: readUrl }); |
| 69 | +}); |
0 commit comments