diff --git a/packages/store-s3/index.js b/packages/store-s3/index.js index d2b07026e..64f961515 100644 --- a/packages/store-s3/index.js +++ b/packages/store-s3/index.js @@ -61,6 +61,26 @@ export default class S3Store { return client; } + /** + * Check if file exists + * @param {string} filePath - Path to file + * @returns {Promise} File exists + */ + async fileExists(filePath) { + try { + const getCommand = new GetObjectCommand({ + Bucket: this.options.bucket, + Key: filePath, + }); + + await this.client().send(getCommand); + + return true; + } catch { + return false; + } + } + /** * Create file * @param {string} filePath - Path to file @@ -75,6 +95,11 @@ export default class S3Store { }); try { + const fileExists = await this.fileExists(filePath); + if (fileExists) { + return; + } + const { ETag } = await this.client().send(putCommand); if (ETag) { diff --git a/packages/store-s3/test/index.js b/packages/store-s3/test/index.js index cc1dc0189..cfba07144 100644 --- a/packages/store-s3/test/index.js +++ b/packages/store-s3/test/index.js @@ -42,7 +42,16 @@ describe("store-s3", () => { assert.equal(indiekit.publication.store.info.name, "website bucket"); }); + it("Checks if file exists", async () => { + mockS3Client.on(GetObjectCommand).resolves({ ETag: "true" }); + assert.equal(await s3.fileExists("foo.md"), true); + + mockS3Client.on(GetObjectCommand).rejects("Couldn’t get object"); + assert.equal(await s3.fileExists("foo.md"), false); + }); + it("Creates file", async () => { + mockS3Client.on(GetObjectCommand).rejects("Couldn’t get object"); mockS3Client.on(PutObjectCommand).resolves({ ETag: "true" }); assert.equal( @@ -51,7 +60,14 @@ describe("store-s3", () => { ); }); + it("Doesn’t create file if already exists", async () => { + mockS3Client.on(GetObjectCommand).resolves({ ETag: "true" }); + + assert.equal(await s3.createFile("foo.md", "foobar"), undefined); + }); + it("Throws error creating file", async () => { + mockS3Client.on(GetObjectCommand).rejects("Couldn’t get object"); mockS3Client.on(PutObjectCommand).rejects("Couldn’t put object"); await assert.rejects(s3.createFile("foo.md", ""), {