|
| 1 | +/* eslint-disable @typescript-eslint/only-throw-error */ |
| 2 | + |
1 | 3 | import { auth } from "@clerk/nextjs/server"; |
2 | 4 | import { createUploadthing, type FileRouter } from "uploadthing/next"; |
3 | 5 | import { UploadThingError } from "uploadthing/server"; |
| 6 | +import { z } from "zod"; |
4 | 7 |
|
5 | 8 | import * as mutations from "~/server/db/mutations"; |
| 9 | +import * as queries from "~/server/db/queries"; |
6 | 10 |
|
7 | 11 | const f = createUploadthing(); |
8 | 12 |
|
9 | 13 | export const ourFileRouter = { |
10 | 14 | imageUploader: f({ image: { maxFileSize: "4MB", maxFileCount: 1 } }) |
11 | | - .middleware(async () => { |
| 15 | + .input(z.object({ folderId: z.number() })) |
| 16 | + .middleware(async ({ input }) => { |
12 | 17 | const user = await auth(); |
13 | | - |
14 | | - // eslint-disable-next-line @typescript-eslint/only-throw-error |
15 | 18 | if (!user.userId) throw new UploadThingError("Unauthorized"); |
16 | 19 |
|
17 | | - return { userId: user.userId }; |
| 20 | + const folder = await queries.getFolderById(input.folderId); |
| 21 | + if (!folder) throw new UploadThingError("Folder not found"); |
| 22 | + |
| 23 | + if (folder.ownerId !== user.userId) |
| 24 | + throw new UploadThingError("Unauthorized"); |
| 25 | + |
| 26 | + return { userId: user.userId, parent: folder.id }; |
18 | 27 | }) |
19 | 28 | .onUploadComplete(async ({ metadata, file }) => { |
20 | 29 | console.log("Upload complete for userId:", metadata.userId); |
21 | 30 | console.log("file url", file.ufsUrl); |
22 | 31 |
|
23 | | - const uploadedFile = { ...file, parent: 0 }; |
| 32 | + const uploadedFile = { ...file, parent: metadata.parent }; |
24 | 33 | await mutations.createFile(uploadedFile, metadata.userId); |
25 | 34 |
|
26 | 35 | return { uploadedBy: metadata.userId }; |
|
0 commit comments