Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat: Revise createFile logic to return modified filenames and location #242

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,16 +139,23 @@ class S3Adapter {

// For a given config object, filename, and data, store a file in S3
// Returns a promise containing the S3 object creation response
async createFile(filename, data, contentType, options = {}) {
async createFile(filename, data, contentType, options = {}, config = {}) {

let key_without_prefix = filename;
if (this._generateKey instanceof Function) {
try {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe removing the try block would achieve the same result while preserving the original error trace and improving readability.

key_without_prefix = this._generateKey(filename, contentType, options);
}catch(e){
throw new Error(e); // throw error if generateKey function fails
}
}

const params = {
Bucket: this._bucket,
Key: this._bucketPrefix + filename,
Key: this._bucketPrefix + key_without_prefix,
Body: data,
};

if (this._generateKey instanceof Function) {
params.Key = this._bucketPrefix + this._generateKey(filename);
}
if (this._fileAcl) {
if (this._fileAcl === 'none') {
delete params.ACL;
Expand Down Expand Up @@ -180,7 +187,17 @@ class S3Adapter {
const endpoint = this._endpoint || `https://${this._bucket}.s3.${this._region}.amazonaws.com`;
const location = `${endpoint}/${params.Key}`;

return Object.assign(response || {}, { Location: location });
let url;
if (Object.keys(config).length != 0) { // if config is passed, we can generate a presigned url here
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of checking only for the presence of keys, let's ensure we are checking for the correct keys.

Maybe change to:
if (config?.mount && config?.applicationId)

url = await this.getFileLocation(config, key_without_prefix);
}

return {
location: location, // actual upload location, used for tests
name: key_without_prefix, // filename in storage, consistent with other adapters
s3_response: response, // raw s3 response
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we don't need the s3_response key and we can remove it.

...url ? { url: url } : {} // url (optionally presigned) or non-direct access url
};
}

async deleteFile(filename) {
Expand Down
55 changes: 52 additions & 3 deletions spec/test.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -696,7 +696,7 @@ describe('S3Adapter tests', () => {
const s3 = getMockS3Adapter(options);
const fileName = 'randomFileName.txt';
const response = s3.createFile(fileName, 'hello world', 'text/utf8').then(value => {
const url = new URL(value.Location);
const url = new URL(value.location);
expect(url.pathname.indexOf(fileName) > 13).toBe(true);
});
promises.push(response);
Expand All @@ -707,7 +707,7 @@ describe('S3Adapter tests', () => {
const s3 = getMockS3Adapter(options);
const fileName = 'foo/randomFileName.txt';
const response = s3.createFile(fileName, 'hello world', 'text/utf8').then(value => {
const url = new URL(value.Location);
const url = new URL(value.location);
expect(url.pathname.substring(1)).toEqual(options.bucketPrefix + fileName);
});
promises.push(response);
Expand All @@ -717,7 +717,7 @@ describe('S3Adapter tests', () => {
const s3 = getMockS3Adapter(options);
const fileName = 'foo/randomFileName.txt';
const response = s3.createFile(fileName, 'hello world', 'text/utf8').then(value => {
const url = new URL(value.Location);
const url = new URL(value.location);
expect(url.pathname.indexOf('foo/')).toEqual(6);
expect(url.pathname.indexOf('random') > 13).toBe(true);
});
Expand Down Expand Up @@ -834,6 +834,55 @@ describe('S3Adapter tests', () => {
expect(commandArg).toBeInstanceOf(PutObjectCommand);
expect(commandArg.input.ACL).toBeUndefined();
});

it('should return url when config is provided', async () => {
const options = {
bucket: 'bucket-1',
presignedUrl: true
};
const s3 = new S3Adapter(options);

const mockS3Response = {
ETag: '"mock-etag"',
VersionId: 'mock-version',
Location: 'mock-location'
};
s3ClientMock.send.and.returnValue(Promise.resolve(mockS3Response));
s3._s3Client = s3ClientMock;

// Mock getFileLocation to return a presigned URL
spyOn(s3, 'getFileLocation').and.returnValue(Promise.resolve('https://presigned-url.com/file.txt'));

const result = await s3.createFile(
'file.txt',
'hello world',
'text/utf8',
{},
{ mount: 'http://example.com', applicationId: 'test123' }
);

expect(result).toEqual({
location: jasmine.any(String),
name: 'file.txt',
s3_response: jasmine.any(Object),
url: 'https://presigned-url.com/file.txt'
});
});

it('should handle generateKey function errors', async () => {
const options = {
bucket: 'bucket-1',
generateKey: () => {
throw 'Generate key failed';
}
};
const s3 = new S3Adapter(options);
s3._s3Client = s3ClientMock;

await expectAsync(
s3.createFile('file.txt', 'hello world', 'text/utf8', {})
).toBeRejectedWithError('Generate key failed');
});
});

describe('handleFileStream', () => {
Expand Down