| 1 | import { ConfigService } from '@nestjs/config'; |
| 2 | import { Test, type |
| 3 | import { beforeEach, describe |
| 4 | |
| 5 | import { |
| 6 | EmptyAvatarError, |
| 7 | UnsupportedAvatarTypeError, |
| 8 | } from '../../lib/avatars/avatar.errors.js'; |
| 9 | import { S3Service } |
| 10 | import { AvatarStorageService } |
| 11 | |
| 12 | const png = Buffer |
| 13 | |
| 14 | describe('AvatarStorageService', () |
| 15 | let service: |
| 16 | let s3: |
| 17 | bucket: string |
| 18 | putObject: ReturnType |
| 19 | deleteUnder: ReturnType |
| 20 | }; |
| 21 | |
| 22 | beforeEach(async () |
| 23 | s3 = { |
| 24 | bucket: 'ghost', |
| 25 | putObject: vi.fn |
| 26 | deleteUnder: vi.fn |
| 27 | }; |
| 28 | |
| 29 | const module: |
| 30 | providers: [ |
| 31 | AvatarStorageService, |
| 32 | { provide: S3Service, |
| 33 | { |
| 34 | provide: ConfigService, |
| 35 | useValue: { getOrThrow: |
| 36 | }, |
| 37 | ], |
| 38 | }).compile(); |
| 39 | |
| 40 | service = module. |
| 41 | }); |
| 42 | |
| 43 | it('stores the bytes under the owner and returns a servable URL', |
| 44 | const { url |
| 45 | ownerId: 'user-1', |
| 46 | contentType: 'image/png', |
| 47 | body: png, |
| 48 | }); |
| 49 | |
| 50 | expect(s3.putObject |
| 51 | expect.objectContaining({ |
| 52 | Bucket: 'ghost', |
| 53 | Body: png, |
| 54 | ContentType: 'image/png', |
| 55 | }), |
| 56 | ); |
| 57 | |
| 58 | const { Key |
| 59 | expect(Key).toMatch |
| 60 | expect(url).toBe |
| 61 | }); |
| 62 | |
| 63 | it('drops the superseded avatars but keeps the one just written', |
| 64 | await service.store |
| 65 | ownerId: 'user-1', |
| 66 | contentType: 'image/png', |
| 67 | body: png, |
| 68 | }); |
| 69 | |
| 70 | const written: |
| 71 | expect(s3.deleteUnder |
| 72 | }); |
| 73 | |
| 74 | it('refuses anything that is not an allowed image, and empty bodies', |
| 75 | await expect( |
| 76 | service.store({ |
| 77 | ownerId: 'user-1', |
| 78 | contentType: 'text/html', |
| 79 | body: png, |
| 80 | }), |
| 81 | ).rejects.toBeInstanceOf( |
| 82 | |
| 83 | await expect( |
| 84 | service.store({ |
| 85 | ownerId: 'user-1', |
| 86 | contentType: 'image/png', |
| 87 | body: Buffer.alloc |
| 88 | }), |
| 89 | ).rejects.toBeInstanceOf( |
| 90 | |
| 91 | expect(s3.putObject |
| 92 | }); |
| 93 | |
| 94 | it('accepts a content type that carries parameters', |
| 95 | await service.store |
| 96 | ownerId: 'user-1', |
| 97 | contentType: 'image/jpeg; charset=binary', |
| 98 | body: png, |
| 99 | }); |
| 100 | |
| 101 | expect(s3.putObject |
| 102 | }); |
| 103 | |
| 104 | it('refuses WebP, which next/og cannot decode', |
| 105 | await expect( |
| 106 | service.store({ |
| 107 | ownerId: 'user-1', |
| 108 | contentType: 'image/webp', |
| 109 | body: png, |
| 110 | }), |
| 111 | ).rejects.toBeInstanceOf( |
| 112 | }); |
| 113 | |
| 114 | it('deletes every avatar the owner has when asked', |
| 115 | await service.remove |
| 116 | |
| 117 | expect(s3.deleteUnder |
| 118 | }); |
| 119 | }); |