Skip to content

Commit e1468c4

Browse files
fix(store-s3): check if file exists before creating
1 parent 101637b commit e1468c4

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

packages/store-s3/index.js

+25
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,26 @@ export default class S3Store {
6161
return client;
6262
}
6363

64+
/**
65+
* Check if file exists
66+
* @param {string} filePath - Path to file
67+
* @returns {Promise<boolean>} File exists
68+
*/
69+
async fileExists(filePath) {
70+
try {
71+
const getCommand = new GetObjectCommand({
72+
Bucket: this.options.bucket,
73+
Key: filePath,
74+
});
75+
76+
await this.client().send(getCommand);
77+
78+
return true;
79+
} catch {
80+
return false;
81+
}
82+
}
83+
6484
/**
6585
* Create file
6686
* @param {string} filePath - Path to file
@@ -75,6 +95,11 @@ export default class S3Store {
7595
});
7696

7797
try {
98+
const fileExists = await this.fileExists(filePath);
99+
if (fileExists) {
100+
return;
101+
}
102+
78103
const { ETag } = await this.client().send(putCommand);
79104

80105
if (ETag) {

packages/store-s3/test/index.js

+16
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,16 @@ describe("store-s3", () => {
4242
assert.equal(indiekit.publication.store.info.name, "website bucket");
4343
});
4444

45+
it("Checks if file exists", async () => {
46+
mockS3Client.on(GetObjectCommand).resolves({ ETag: "true" });
47+
assert.equal(await s3.fileExists("foo.md"), true);
48+
49+
mockS3Client.on(GetObjectCommand).rejects("Couldn’t get object");
50+
assert.equal(await s3.fileExists("foo.md"), false);
51+
});
52+
4553
it("Creates file", async () => {
54+
mockS3Client.on(GetObjectCommand).rejects("Couldn’t get object");
4655
mockS3Client.on(PutObjectCommand).resolves({ ETag: "true" });
4756

4857
assert.equal(
@@ -51,7 +60,14 @@ describe("store-s3", () => {
5160
);
5261
});
5362

63+
it("Doesn’t create file if already exists", async () => {
64+
mockS3Client.on(GetObjectCommand).resolves({ ETag: "true" });
65+
66+
assert.equal(await s3.createFile("foo.md", "foobar"), undefined);
67+
});
68+
5469
it("Throws error creating file", async () => {
70+
mockS3Client.on(GetObjectCommand).rejects("Couldn’t get object");
5571
mockS3Client.on(PutObjectCommand).rejects("Couldn’t put object");
5672

5773
await assert.rejects(s3.createFile("foo.md", ""), {

0 commit comments

Comments
 (0)