From 5c300e9e976a7b211adc0f5c1c646c068df240b1 Mon Sep 17 00:00:00 2001 From: Finn Michael Halvorsen Date: Fri, 9 Jul 2021 13:06:11 +0200 Subject: [PATCH] feat(s3bucket): added support for listing objects in a bucket via listObjects --- src/s3/S3Bucket.ts | 10 ++++++++++ test/test.ts | 37 +++++++++++++++++++++++++++++++++---- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/s3/S3Bucket.ts b/src/s3/S3Bucket.ts index 41f5c07..370cdee 100644 --- a/src/s3/S3Bucket.ts +++ b/src/s3/S3Bucket.ts @@ -103,4 +103,14 @@ export class S3Bucket { return false; } } + + async listObjects(prefix?: string, startAfter?: string) { + return await this.s3 + .listObjectsV2({ + Bucket: this.name, + Prefix: prefix, + StartAfter: startAfter, + }) + .promise(); + } } diff --git a/test/test.ts b/test/test.ts index 033e544..8e55e83 100644 --- a/test/test.ts +++ b/test/test.ts @@ -7,10 +7,6 @@ configure({region: 'eu-west-1'}); const testBucketName = 'tibber-tibber-ftw-123321'; describe('getBucket', () => { - beforeEach(async () => { - await S3Bucket.deleteIfExsists(testBucketName); - }); - it('should be able to create bucket', async () => { const result = await S3Bucket.getBucket(testBucketName); expect(typeof result).toBe('object'); @@ -88,6 +84,39 @@ describe('getBucket', () => { result = await bucket.objectAvailable(name); expect(result).toBe(false); }); + + it('should be able to list objects', async () => { + const bucket = await S3Bucket.getBucket(testBucketName); + + const res = await bucket.listObjects(); + + const contents = res.Contents || []; + + expect(contents.length).toBeGreaterThan(10); + }); + + it('should be able to list objects with prefix', async () => { + const bucket = await S3Bucket.getBucket(testBucketName); + + const res = await bucket.listObjects('test'); + + const contents = res.Contents || []; + + expect(contents).toHaveLength(2); + }); + + it('should be able to list after a given key', async () => { + const bucket = await S3Bucket.getBucket(testBucketName); + + const buffer = Buffer.from([8, 6, 7, 5, 3, 0, 9]); + await bucket.putObject('test2', buffer); + + const res = await bucket.listObjects('test', 'test'); + + const contents = res.Contents || []; + + expect(contents).toHaveLength(1); + }); }); it('should be able to assign several topics to builder', () => {