Skip to content

Commit

Permalink
fix(store-s3): check if file exists before creating
Browse files Browse the repository at this point in the history
  • Loading branch information
paulrobertlloyd committed Oct 8, 2024
1 parent 101637b commit e1468c4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
25 changes: 25 additions & 0 deletions packages/store-s3/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,26 @@ export default class S3Store {
return client;
}

/**
* Check if file exists
* @param {string} filePath - Path to file
* @returns {Promise<boolean>} 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
Expand All @@ -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) {
Expand Down
16 changes: 16 additions & 0 deletions packages/store-s3/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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", ""), {
Expand Down

0 comments on commit e1468c4

Please sign in to comment.