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