Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Feature/add utility functions for uploads #17

Merged
merged 6 commits into from
Dec 27, 2023
Merged
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
6 changes: 6 additions & 0 deletions __mocks__/crypto.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// __mocks__/crypto.js
const crypto = jest.createMockFromModule('crypto');

crypto.randomUUID = () => '123e4567-e89b-12d3-a456-426614174000';

module.exports = crypto;
128 changes: 128 additions & 0 deletions __tests__/storage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import {
uploadMedia,
getS3Client,
getS3PutUrl,
getS3ReadUrl,
} from '../src/storage';
import {
S3Client,
PutObjectCommand,
GetObjectCommand,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
jest.mock('@aws-sdk/client-s3', () => {
return {
S3Client: jest.fn(),
PutObjectCommand: jest.fn(),
GetObjectCommand: jest.fn(),
};
});
jest.mock('../src/utils', () => {
return {
generateFilePath: jest.fn(() => 'pid/mockPath'),
};
});
jest.mock('@aws-sdk/s3-request-presigner', () => {
return {
getSignedUrl: jest.fn(() => Promise.resolve('mockSignedUrl')),
};
});

describe('uploadMedia', () => {
it('should upload media and return the upload status and URL', async () => {
// Mock the fetch function
global.fetch = jest.fn().mockImplementation((url, options) => {
if (url.includes('/api/media')) {
return Promise.resolve({
json: () =>
Promise.resolve({ putUrl: 'mockPutUrl', getUrl: 'mockGetUrl' }),
});
}
return Promise.resolve({ ok: true });
});

const mockFile = new File([''], 'testfile.png', { type: 'image/png' });
const result = await uploadMedia('http://backendRoute', mockFile);

expect(result).toEqual({ status: true, uploadedUrl: 'mockGetUrl' });
expect(fetch).toHaveBeenCalledTimes(2);
});

it('should throw an error when the fetch to the backend fails', async () => {
// Mock the fetch function to simulate a failure
global.fetch = jest
.fn()
.mockImplementation(() => Promise.reject(new Error('Network failure')));

const mockFile = new File([''], 'testfile.png', { type: 'image/png' });

await expect(uploadMedia('http://backendRoute', mockFile)).rejects.toThrow(
'Network failure'
);

expect(fetch).toHaveBeenCalledWith(expect.any(String), expect.any(Object));
});
});

describe('getS3Client', () => {
it('should create an S3 client with specified region and credentials', () => {
const mockCredentials = { accessKeyId: 'key', secretAccessKey: 'secret' };
const client = getS3Client('us-west-2', mockCredentials);

expect(client).toBeInstanceOf(S3Client);
// Additional assertions to check if the client was configured correctly
});
});

describe('getS3PutUrl', () => {
it('should create a pre-signed PUT URL for S3', async () => {
const mockClient = new S3Client({ region: 'mock-region' });
const mockFile = new File([''], 'testfile.png', { type: 'image/png' });

const result = await getS3PutUrl(
'my-bucket',
'promo-id',
mockFile,
mockClient
);

expect(PutObjectCommand).toHaveBeenCalledWith({
Key: 'pid/mockPath',
ContentType: 'image/png',
Bucket: 'my-bucket',
});
expect(getSignedUrl).toHaveBeenCalledWith(
mockClient,
expect.any(PutObjectCommand),
{ expiresIn: 600 }
);
expect(result).toEqual({
putUrl: 'mockSignedUrl',
awsPath: 'pid/mockPath',
});
});

// Additional tests can be added to cover different scenarios
});

describe('getS3ReadUrl', () => {
it('should create a pre-signed GET URL for S3', async () => {
const mockClient = new S3Client({ region: 'mock-region' });
const mockPath = 's3://my-bucket/pid/mockPath';

const result = await getS3ReadUrl(mockPath, mockClient);

expect(GetObjectCommand).toHaveBeenCalledWith({
Key: 'pid/mockPath',
Bucket: 'my-bucket',
});
expect(getSignedUrl).toHaveBeenCalledWith(
mockClient,
expect.any(GetObjectCommand),
{ expiresIn: 600 }
);
expect(result).toEqual({ getUrl: 'mockSignedUrl' });
});

// Additional tests can be added for different scenarios and error handling
});
18 changes: 18 additions & 0 deletions __tests__/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { generateFilePath } from '../src/utils'; // Adjust the import according to your file structure

describe('generateFilePath', () => {
// Mocking the crypto module
jest.mock('crypto');
it('should generate a correct file path based on the given file and promo ID', () => {
// Mocking a File object
const mockFile = new File([''], 'testfile.png', { type: 'image/png' });

const promoId = 'promo123';
const expectedFileExtension = `.png`;

const result = generateFilePath(mockFile, promoId);

expect(result).toContain(expectedFileExtension);
expect(result).toContain(promoId);
});
});
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@
}
],
"devDependencies": {
"@aws-sdk/client-s3": "^3.481.0",
"@aws-sdk/s3-request-presigner": "^3.481.0",
"@size-limit/preset-small-lib": "^7.0.8",
"@testing-library/react": "~12",
"@tsconfig/create-react-app": "^1.0.2",
Expand Down
19 changes: 18 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,19 @@
import { getWidget, getWidgetCallback, showWidget } from './cloudinary-utils';
import defaultOptions from './defaultOptions';
import { VIDEO_EXTENSIONS, IMAGE_EXTENSIONS } from './constants';
import { fetcher, detectMediaType, getOptions } from './utils';
import {
fetcher,
detectMediaType,
getOptions,
generateFilePath,

Check warning on line 10 in src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 18.x and ubuntu-latest

'generateFilePath' is defined but never used

Check warning on line 10 in src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 18.x and windows-latest

'generateFilePath' is defined but never used

Check warning on line 10 in src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 18.x and macOS-latest

'generateFilePath' is defined but never used

Check warning on line 10 in src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20.x and ubuntu-latest

'generateFilePath' is defined but never used

Check warning on line 10 in src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20.x and windows-latest

'generateFilePath' is defined but never used

Check warning on line 10 in src/index.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node 20.x and macOS-latest

'generateFilePath' is defined but never used
} from './utils';
import {
uploadMedia,
getS3Client,
getS3PutUrl,
getS3ReadUrl,
S3Credentials,
} from './storage';
export {
generateAccessToken,
getToken,
Expand All @@ -16,4 +28,9 @@
fetcher,
detectMediaType,
getOptions,
uploadMedia,
getS3Client,
getS3PutUrl,
getS3ReadUrl,
};
export type { S3Credentials };
100 changes: 100 additions & 0 deletions src/storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import {
S3Client,
PutObjectCommand,
GetObjectCommand,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { generateFilePath } from './utils';
/**
* uploadMedia
* @description Upload a file to AWS S3 given a backend route and the file.
* The server at the given `backendRoute` should return a pre-signed URL for uploading the file and
* one for reading the file.
*
*/
export async function uploadMedia(backendRoute: string, file: File) {
try {
const res = await fetch(`${backendRoute}/api/media`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
fileName: file.name,
fileType: file.type,
fileSize: file.size,
}),
});

const { putUrl, getUrl } = await res.json();

const uploadResponse = await fetch(putUrl, {
body: file,
method: 'PUT',
headers: { 'Content-Type': file.type },
});

return { status: uploadResponse.ok, uploadedUrl: getUrl };
} catch (error) {
console.error(error);
throw error;
}
}
export type S3Credentials = {
accessKeyId: string;
secretAccessKey: string;
};

/**
* getS3Client
* @description Get the client instance of the AWS S3 service.
*/
export function getS3Client(region: string, credentials: S3Credentials) {
return new S3Client({
region: region,
credentials: credentials,
});
}

/**
* getS3PutUrl
* @description Given the bucket base, Promo ID and file object, return a pre-signed URL for uploading the file.
*/
export async function getS3PutUrl(
bucketName: string,
pid: string,
file: File,
client: S3Client,
expiresInSeconds?: number
) {
const awsPath = generateFilePath(file, pid);
const putCommand = new PutObjectCommand({
Key: awsPath,
ContentType: file.type,
Bucket: bucketName,
});
const signedPutUrl = await getSignedUrl(client, putCommand, {
expiresIn: expiresInSeconds || 600,
});
return { putUrl: signedPutUrl, awsPath };
}

/**
* getS3ReadUrl
* @description Given the awsPath and S3Client, return a pre-signed URL for reading the file.
*/
export async function getS3ReadUrl(
awsPath: string,
client: S3Client,
expiresInSeconds?: number
) {
let key = awsPath.split('/').slice(3).join('/');
let bucket = awsPath.split('/').slice(2, 3).join();
const getCommand = new GetObjectCommand({
Key: key,
Bucket: bucket,
});
// Generate pre-signed URL for GET request
const signedGetUrl = await getSignedUrl(client, getCommand, {
expiresIn: expiresInSeconds || 600,
});
return { getUrl: signedGetUrl };
}
20 changes: 19 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import { IMAGE_EXTENSIONS, VIDEO_EXTENSIONS } from './constants';
import defaultOptions from './defaultOptions';
import crypto from 'crypto';
/**
* A fetcher for useSwr
*
Expand Down Expand Up @@ -54,5 +55,22 @@ function detectMediaType(url: string) {
function getOptions(options?: object | undefined) {
return Object.assign(options || {}, defaultOptions);
}

/**
* generateFilePath
*
* @description Given a file and Promo ID, generate a proper file path.
*
* @param file A File object
* @param pid A string Promo ID
*
* @returns string File path
*/
function generateFilePath(file: File, pid: string) {
const mimeType = file.type;
let ext: string = mimeType.slice(6);
const uuid = crypto.randomUUID();
return `${pid}/${uuid}.${ext}`;
}
// Fall back to default handling
export { fetcher, detectMediaType, getOptions };
export { fetcher, detectMediaType, getOptions, generateFilePath };
Loading
Loading