diff --git a/src/s3/S3Bucket.ts b/src/s3/S3Bucket.ts index 60d815e..f81fd60 100644 --- a/src/s3/S3Bucket.ts +++ b/src/s3/S3Bucket.ts @@ -134,4 +134,8 @@ export class S3Bucket { StartAfter: startAfter, }); } + + async deleteObject(key: string) { + return await this.s3.deleteObject({Bucket: this.name, Key: key}); + } } diff --git a/test/s3.test.ts b/test/s3.test.ts index 3319d9e..4280805 100644 --- a/test/s3.test.ts +++ b/test/s3.test.ts @@ -1,5 +1,6 @@ import rand from 'randomstring'; import {S3Bucket, configure} from '../src'; +import {NoSuchKey} from '@aws-sdk/client-s3'; const localstackEndpoint = process.env.LOCALSTACK_ENDPOINT || 'http://localhost:4566'; @@ -59,6 +60,36 @@ describe('getExistingBucket', () => { }); }); +describe('deleteObject', () => { + it('should be able to delete object', async () => { + const bucket = await S3Bucket.getOrCreateBucket( + generateRandomBucketName(), + localstackEndpoint + ); + const buffer = Buffer.from([8, 6, 7, 5, 3, 0, 9]); + await bucket!.putObject('test', buffer, 'image/png'); + const buffer2 = Buffer.from([8, 6, 7, 5, 3, 0, 9]); + await bucket!.putObject('test2', buffer2, 'image/png'); + + let list = await bucket?.listObjects(); + expect(list?.Contents?.length).toBe(2); + + await bucket!.deleteObject('test'); + + list = await bucket?.listObjects(); + expect(list?.Contents?.length).toBe(1); + + expect(async () => { + await bucket?.getObject('test'); + }).rejects.toThrow(NoSuchKey); + + await bucket!.deleteObject('test2'); + + list = await bucket?.listObjects(); + expect(list?.Contents).toBe(undefined); + }); +}); + describe('deleteIfExsists', () => { it('should be able to delete bucket', async () => { const testBucketName = generateRandomBucketName();