|
| 1 | +import { db } from '@oyster/db'; |
| 2 | +import { id } from '@oyster/utils'; |
| 3 | + |
| 4 | +import { |
| 5 | + deleteObject, |
| 6 | + putObject, |
| 7 | + R2_PUBLIC_BUCKET_NAME, |
| 8 | + R2_PUBLIC_BUCKET_URL, |
| 9 | +} from '@/infrastructure/s3'; |
| 10 | + |
| 11 | +type UploadProfilePictureInput = { |
| 12 | + memberId: string; |
| 13 | + pictureUrl: string; |
| 14 | +}; |
| 15 | + |
| 16 | +/** |
| 17 | + * Uploads a profile picture to S3 and updates the member's profile picture in |
| 18 | + * the database. It first fetches the picture from the URL (either coming |
| 19 | + * from LinkedIn or Slack) and effecitvielly "copies" the contents to S3. |
| 20 | + * |
| 21 | + * @param input - The input for the upload profile picture use case. |
| 22 | + * @returns The updated member's profile picture. |
| 23 | + */ |
| 24 | +export async function uploadProfilePicture({ |
| 25 | + memberId, |
| 26 | + pictureUrl, |
| 27 | +}: UploadProfilePictureInput) { |
| 28 | + const member = await db |
| 29 | + .selectFrom('students') |
| 30 | + .select(['profilePicture', 'profilePictureKey']) |
| 31 | + .where('id', '=', memberId) |
| 32 | + .executeTakeFirst(); |
| 33 | + |
| 34 | + if (!member) { |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + const response = await fetch(pictureUrl); |
| 39 | + |
| 40 | + if (!response.ok) { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + const arrayBuffer = await response.arrayBuffer(); |
| 45 | + const buffer = Buffer.from(arrayBuffer); |
| 46 | + |
| 47 | + const contentType = response.headers.get('content-type'); |
| 48 | + |
| 49 | + const extension = contentType?.includes('image/') |
| 50 | + ? contentType.split('/')[1] |
| 51 | + : null; |
| 52 | + |
| 53 | + const key = extension ? `members/${id()}.${extension}` : `members/${id()}`; |
| 54 | + |
| 55 | + await putObject({ |
| 56 | + bucket: R2_PUBLIC_BUCKET_NAME, |
| 57 | + content: buffer, |
| 58 | + contentType: contentType || undefined, |
| 59 | + key, |
| 60 | + }); |
| 61 | + |
| 62 | + await db |
| 63 | + .updateTable('students') |
| 64 | + .set({ |
| 65 | + profilePicture: `${R2_PUBLIC_BUCKET_URL}/${key}`, |
| 66 | + profilePictureKey: key, |
| 67 | + }) |
| 68 | + .where('id', '=', memberId) |
| 69 | + .execute(); |
| 70 | + |
| 71 | + if (member.profilePictureKey) { |
| 72 | + await deleteObject({ |
| 73 | + bucket: R2_PUBLIC_BUCKET_NAME, |
| 74 | + key: member.profilePictureKey, |
| 75 | + }); |
| 76 | + } |
| 77 | + |
| 78 | + return { |
| 79 | + profilePicture: `${R2_PUBLIC_BUCKET_URL}/${key}`, |
| 80 | + profilePictureKey: key, |
| 81 | + }; |
| 82 | +} |
0 commit comments