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

fix(uploads): avoid making redundant memory copies #91

Merged
merged 1 commit into from
Sep 5, 2024
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
8 changes: 5 additions & 3 deletions src/uploads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,10 @@ export async function toFile(
// If it's a promise, resolve it.
value = await value;

// Use the file's options if there isn't one provided
options ??= isFileLike(value) ? { lastModified: value.lastModified, type: value.type } : {};
// If we've been given a `File` we don't need to do anything
if (isFileLike(value)) {
return value;
}

if (isResponseLike(value)) {
const blob = await value.blob();
Expand All @@ -126,7 +128,7 @@ export async function toFile(

name ||= getName(value) ?? 'unknown_file';

if (!options.type) {
if (!options?.type) {
const type = (bits[0] as any)?.type;
if (typeof type === 'string') {
options = { ...options, type };
Expand Down
8 changes: 8 additions & 0 deletions tests/uploads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,12 @@ describe('toFile', () => {
const file = await toFile(input);
expect(file.name).toEqual('uploads.test.ts');
});

it('does not copy File objects', async () => {
const input = new File(['foo'], 'input.jsonl', { type: 'jsonl' });
const file = await toFile(input);
expect(file).toBe(input);
expect(file.name).toEqual('input.jsonl');
expect(file.type).toBe('jsonl');
});
});