| 1 | import type { Readable } from 'node:stream'; |
| 2 | |
| 3 | import { Injectable } |
| 4 | import { ConfigService } |
| 5 | import { nanoid } |
| 6 | |
| 7 | import { |
| 8 | AVATAR_CONTENT_TYPES, |
| 9 | AVATAR_NAME_PATTERN, |
| 10 | AVATAR_PREFIX, |
| 11 | type AvatarContentType, |
| 12 | } from '../../lib/avatars/avatar.constants.js'; |
| 13 | import { |
| 14 | AvatarNotFoundError, |
| 15 | EmptyAvatarError, |
| 16 | UnsupportedAvatarTypeError, |
| 17 | } from '../../lib/avatars/avatar.errors.js'; |
| 18 | import { S3Service } |
| 19 | |
| 20 | export type AvatarObject |
| 21 | stream: Readable |
| 22 | contentType: string |
| 23 | size?: number |
| 24 | }; |
| 25 | |
| 26 | /** Pictures for accounts and organizations, one live object per owner, keyed by the owner's id. */ |
| 27 | @Injectable() |
| 28 | export class AvatarStorageService |
| 29 | private readonly publicUrl |
| 30 | |
| 31 | constructor( |
| 32 | private readonly s3 |
| 33 | configService: ConfigService |
| 34 | ) { |
| 35 | this.publicUrl = |
| 36 | .getOrThrow<string>( |
| 37 | .replace(/\/+ |
| 38 | } |
| 39 | |
| 40 | async store({ |
| 41 | ownerId, |
| 42 | contentType, |
| 43 | body, |
| 44 | }: { |
| 45 | ownerId: string |
| 46 | contentType: string |
| 47 | body: Buffer |
| 48 | }) { |
| 49 | const extension = |
| 50 | AVATAR_CONTENT_TYPES[ |
| 51 | contentType.split('; |
| 52 | ]; |
| 53 | |
| 54 | if (!extension) |
| 55 | if (!body?.length |
| 56 | |
| 57 | const name = |
| 58 | |
| 59 | await this.s3 |
| 60 | Bucket: this.s3 |
| 61 | Key: this.key |
| 62 | Body: body, |
| 63 | ContentType: contentType, |
| 64 | }); |
| 65 | |
| 66 | await this.removeAll |
| 67 | |
| 68 | return { url: |
| 69 | } |
| 70 | |
| 71 | async remove(ownerId |
| 72 | await this.removeAll |
| 73 | } |
| 74 | |
| 75 | async get(ownerId |
| 76 | // Only names this service generates; nothing user-authored reaches S3. |
| 77 | if (!AVATAR_NAME_PATTERN.test |
| 78 | try { |
| 79 | const object = |
| 80 | Bucket: this.s3 |
| 81 | Key: this.key |
| 82 | }); |
| 83 | |
| 84 | if (!object.Body |
| 85 | |
| 86 | return { |
| 87 | stream: object.Body |
| 88 | contentType: object.ContentType |
| 89 | size: object.ContentLength |
| 90 | }; |
| 91 | } catch (error) |
| 92 | if (error instanceof |
| 93 | throw new AvatarNotFoundError() |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | private key(ownerId |
| 98 | return `${AVATAR_PREFIX} |
| 99 | } |
| 100 | |
| 101 | private async removeAll |
| 102 | await this.s3 |
| 103 | `${AVATAR_PREFIX}/${ownerId |
| 104 | keep ? [this |
| 105 | ); |
| 106 | } |
| 107 | } |