Skip to content
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
70 changes: 39 additions & 31 deletions packages/core/storage-js/src/packages/StorageFileApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,22 +96,11 @@ export default class StorageFileApi extends BaseApiClient<StorageError> {

const metadata = options.metadata

if (typeof Blob !== 'undefined' && fileBody instanceof Blob) {
body = new FormData()
body.append('cacheControl', options.cacheControl as string)
if (metadata) {
body.append('metadata', this.encodeMetadata(metadata))
}
body.append('', fileBody)
} else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) {
body = fileBody
// Only append if not already present
if (!body.has('cacheControl')) {
body.append('cacheControl', options.cacheControl as string)
}
if (metadata && !body.has('metadata')) {
body.append('metadata', this.encodeMetadata(metadata))
}
if (
(typeof Blob !== 'undefined' && fileBody instanceof Blob) ||
(typeof FormData !== 'undefined' && fileBody instanceof FormData)
) {
body = this.prepareUploadFormData(fileBody, options)
} else {
body = fileBody
headers['cache-control'] = `max-age=${options.cacheControl}`
Expand Down Expand Up @@ -295,21 +284,11 @@ export default class StorageFileApi extends BaseApiClient<StorageError> {

const metadata = options.metadata

if (typeof Blob !== 'undefined' && fileBody instanceof Blob) {
body = new FormData()
body.append('cacheControl', options.cacheControl as string)
if (metadata) {
body.append('metadata', this.encodeMetadata(metadata))
}
body.append('', fileBody)
} else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) {
body = fileBody
if (!body.has('cacheControl')) {
body.append('cacheControl', options.cacheControl as string)
}
if (metadata && !body.has('metadata')) {
body.append('metadata', this.encodeMetadata(metadata))
}
if (
(typeof Blob !== 'undefined' && fileBody instanceof Blob) ||
(typeof FormData !== 'undefined' && fileBody instanceof FormData)
) {
body = this.prepareUploadFormData(fileBody, options)
} else {
body = fileBody
headers['cache-control'] = `max-age=${options.cacheControl}`
Expand Down Expand Up @@ -1522,6 +1501,35 @@ export default class StorageFileApi extends BaseApiClient<StorageError> {
})
}

private prepareUploadFormData(fileBody: Blob | FormData, options: FileOptions): FormData {
const body = new FormData()
const files: [string, Blob][] = []

// Storage reads metadata before consuming the file stream.
if (fileBody instanceof FormData) {
fileBody.forEach((value, name) => {
if (typeof value === 'string') {
body.append(name, value)
} else {
files.push([name, value])
}
})
} else {
files.push(['', fileBody])
}

if (!body.has('cacheControl')) {
body.append('cacheControl', options.cacheControl as string)
}
if (options.metadata && !body.has('metadata')) {
body.append('metadata', this.encodeMetadata(options.metadata))
}
for (const [name, file] of files) {
body.append(name, file)
}
return body
}

protected encodeMetadata(metadata: Record<string, any>) {
return JSON.stringify(metadata)
}
Expand Down
10 changes: 5 additions & 5 deletions packages/core/storage-js/test/storageFileApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1295,7 +1295,7 @@ describe('StorageFileApi Edge Cases', () => {

expect(mockPut).toHaveBeenCalled()
const [, , body] = mockPut.mock.calls[0]
expect(body).toBe(testFormData)
expect(body.get('file')).toBe('test content')
})

test('uploadToSignedUrl uses default cacheControl when not provided', async () => {
Expand Down Expand Up @@ -1341,7 +1341,7 @@ describe('StorageFileApi Edge Cases', () => {

expect(mockPost).toHaveBeenCalled()
const [, , body] = mockPost.mock.calls[0] as [null, null, FormData]
expect(body).toBe(testFormData)
expect(body.get('file')).toBe('test content')
expect(body.get('metadata')).toBe(JSON.stringify(metadata))
})

Expand All @@ -1358,7 +1358,7 @@ describe('StorageFileApi Edge Cases', () => {

expect(mockPost).toHaveBeenCalled()
const [, , body, { headers }] = mockPost.mock.calls[0]
expect(body).toBe(testFormData)
expect(body.get('file')).toBe('test content')
expect(headers[testHeaderKey]).toBe(testHeaderValue)
})

Expand Down Expand Up @@ -1425,7 +1425,7 @@ describe('StorageFileApi Edge Cases', () => {

expect(mockPut).toHaveBeenCalled()
const [, , body] = mockPut.mock.calls[0] as [null, null, FormData]
expect(body).toBe(testFormData)
expect(body.get('file')).toBe('test content')
expect(body.get('metadata')).toBe(JSON.stringify(metadata))
})

Expand Down Expand Up @@ -1457,7 +1457,7 @@ describe('StorageFileApi Edge Cases', () => {

expect(mockPut).toHaveBeenCalled()
const [, , body, { headers }] = mockPut.mock.calls[0]
expect(body).toBe(testFormData)
expect(body.get('file')).toBe('test content')
expect(headers[testHeaderKey]).toBe(testHeaderValue)
})

Expand Down
109 changes: 109 additions & 0 deletions packages/core/storage-js/test/storageFileApiUpload.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { StorageClient } from '../src/index'
import { FileOptions } from '../src/lib/types'

type FileBody = Parameters<ReturnType<StorageClient['from']>['upload']>[1]

describe.each(['upload', 'update', 'signed'] as const)(
'%s multipart upload request',
(operation) => {
const bytes = Buffer.from('upload payload')
let fetchMock: jest.MockedFunction<typeof fetch>
let files: ReturnType<StorageClient['from']>

beforeEach(() => {
fetchMock = jest.fn().mockResolvedValue(
new Response(JSON.stringify({ Id: 'object-id', Key: 'bucket/sample.bin' }), {
headers: { 'content-type': 'application/json' },
})
)
files = new StorageClient('http://localhost/storage/v1', {}, fetchMock).from('bucket')
})

async function upload(body: FileBody, options?: FileOptions) {
const result =
operation === 'signed'
? await files.uploadToSignedUrl('sample.bin', 'upload-token', body, options)
: await files[operation]('sample.bin', body, options)
expect(result.error).toBeNull()
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0]
return new Request(url, init)
}

async function expectMultipart(request: Request, fields: Record<string, string>) {
const wire = Buffer.from(await request.arrayBuffer())
const text = wire.toString('latin1')
const filePosition = text.indexOf('filename=')
expect(filePosition).toBeGreaterThan(0)
for (const name of Object.keys(fields)) {
const position = text.indexOf(`name="${name}"`)
expect(position).toBeGreaterThanOrEqual(0)
expect(position).toBeLessThan(filePosition)
}
const parsed = await new Response(wire, { headers: request.headers }).formData()
for (const [name, value] of Object.entries(fields)) {
expect(parsed.getAll(name)).toEqual([value])
}
return parsed
}

test('sends Blob metadata before the file', async () => {
const request = await upload(new Blob([bytes], { type: 'application/octet-stream' }), {
cacheControl: '7200',
metadata: { source: 'blob' },
})
const body = await expectMultipart(request, {
cacheControl: '7200',
metadata: '{"source":"blob"}',
})
const file = body.get('') as File
expect(file.type).toBe('application/octet-stream')
expect(Buffer.from(await file.arrayBuffer())).toEqual(bytes)
})

test('places caller fields and missing options before files without mutating FormData', async () => {
const form = new FormData()
form.append('file', new Blob([bytes]), 'original.bin')
form.append('contentType', 'text/plain')
form.append('tag', 'first')
form.append('tag', 'second')
// A field and a file may share a name; neither should be lost when reordered.
form.append('file', 'text field')
const original: [string, FormDataEntryValue][] = []
form.forEach((value, name) => original.push([name, value]))

const request = await upload(form, {
metadata: { source: 'form' },
})
const body = await expectMultipart(request, {
cacheControl: '3600',
contentType: 'text/plain',
metadata: '{"source":"form"}',
})
expect(body.getAll('tag')).toEqual(['first', 'second'])
const [text, file] = body.getAll('file') as [string, File]
expect(text).toBe('text field')
expect(file.name).toBe('original.bin')
expect(Buffer.from(await file.arrayBuffer())).toEqual(bytes)
const remaining: [string, FormDataEntryValue][] = []
form.forEach((value, name) => remaining.push([name, value]))
expect(remaining).toEqual(original)
})

test('preserves caller metadata over options even when it follows the file', async () => {
const form = new FormData()
form.append('file', new Blob([bytes]), 'original.bin')
form.append('cacheControl', '7200')
form.append('metadata', '{"source":"caller"}')

const request = await upload(form, {
cacheControl: '3600',
metadata: { source: 'options' },
})
await expectMultipart(request, {
cacheControl: '7200',
metadata: '{"source":"caller"}',
})
})
}
)
44 changes: 44 additions & 0 deletions packages/core/supabase-js/test/unit/storageUpload.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { createClient } from '../../src/index'

describe('multipart storage uploads through createClient', () => {
test('sends fields before the file and forwards authentication', async () => {
const fetchMock = jest.fn().mockResolvedValue(
new Response(JSON.stringify({ Id: 'object-id', Key: 'bucket/sample.bin' }), {
headers: { 'content-type': 'application/json' },
})
)
const client = createClient('https://project.supabase.co', 'test-key', {
accessToken: async () => 'test-token',
global: { fetch: fetchMock },
})
const bytes = Buffer.from('upload payload')
const form = new FormData()
form.append('file', new Blob([bytes]), 'sample.bin')
form.append('contentType', 'text/plain')
const { error } = await client.storage.from('bucket').upload('sample.bin', form, {
cacheControl: '7200',
metadata: { source: 'client' },
})

expect(error).toBeNull()
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0]
const request = new Request(url, init)
expect(request.url).toBe('https://project.supabase.co/storage/v1/object/bucket/sample.bin')
expect(request.headers.get('authorization')).toBe('Bearer test-token')
expect(request.headers.get('apikey')).toBe('test-key')
const wire = await request.clone().text()
for (const name of ['contentType', 'cacheControl', 'metadata']) {
const position = wire.indexOf(`name="${name}"`)
expect(position).toBeGreaterThanOrEqual(0)
expect(position).toBeLessThan(wire.indexOf('filename='))
}
const body = await request.formData()
expect(body.get('contentType')).toBe('text/plain')
expect(body.get('cacheControl')).toBe('7200')
expect(body.get('metadata')).toBe('{"source":"client"}')
const file = body.get('file') as File
expect(file.name).toBe('sample.bin')
expect(Buffer.from(await file.arrayBuffer())).toEqual(bytes)
})
})
Loading