|
| 1 | +import { ScriptContext, RuntimeError } from "../_gen/scripts/set_pfp.ts"; |
| 2 | +import { User } from "../utils/types.ts"; |
| 3 | +import { withPfpUrl } from "../utils/pfp.ts"; |
| 4 | + |
| 5 | +export interface Request { |
| 6 | + uploadId: string; |
| 7 | + userToken: string; |
| 8 | +} |
| 9 | + |
| 10 | +export interface Response { |
| 11 | + user: User; |
| 12 | +} |
| 13 | + |
| 14 | +export async function run( |
| 15 | + ctx: ScriptContext, |
| 16 | + req: Request, |
| 17 | +): Promise<Response> { |
| 18 | + // Authenticate/rate limit because this is a public route |
| 19 | + await ctx.modules.rateLimit.throttlePublic({ period: 60, requests: 5 }); |
| 20 | + const { userId } = await ctx.modules.users.authenticateUser({ userToken: req.userToken }); |
| 21 | + |
| 22 | + // Complete the upload in the `uploads` module |
| 23 | + await ctx.modules.uploads.complete({ uploadId: req.uploadId }); |
| 24 | + |
| 25 | + // Delete the old uploaded profile picture and replace it with the new one |
| 26 | + const user = await ctx.db.$transaction(async (db) => { |
| 27 | + // If there is an existing profile picture, delete it |
| 28 | + const oldPfp = await db.pfp.findFirst({ |
| 29 | + where: { userId }, |
| 30 | + select: { uploadId: true }, |
| 31 | + }); |
| 32 | + if (oldPfp) { |
| 33 | + await ctx.modules.uploads.delete({ uploadId: oldPfp.uploadId }); |
| 34 | + await db.pfp.delete({ where: { userId } }); |
| 35 | + } |
| 36 | + |
| 37 | + // Assign the new profile picture to the user |
| 38 | + await db.pfp.create({ |
| 39 | + data: { |
| 40 | + userId, |
| 41 | + uploadId: req.uploadId, |
| 42 | + url: "", |
| 43 | + urlExpiry: new Date(0).toISOString(), |
| 44 | + finishedAt: new Date().toISOString(), |
| 45 | + }, |
| 46 | + }); |
| 47 | + |
| 48 | + // Get the new user object |
| 49 | + const user = await db.user.findFirst({ |
| 50 | + where: { id: userId }, |
| 51 | + select: { |
| 52 | + id: true, |
| 53 | + username: true, |
| 54 | + createdAt: true, |
| 55 | + updatedAt: true, |
| 56 | + }, |
| 57 | + }); |
| 58 | + |
| 59 | + if (!user) { |
| 60 | + throw new RuntimeError("internal_error", { cause: "User not found" }); |
| 61 | + } |
| 62 | + |
| 63 | + return await withPfpUrl( |
| 64 | + ctx, |
| 65 | + user, |
| 66 | + ); |
| 67 | + }); |
| 68 | + |
| 69 | + return { user }; |
| 70 | +} |
| 71 | + |
0 commit comments