Skip to content
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
4 changes: 2 additions & 2 deletions packages/core/storage-js/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ export interface ListBucketOptions {

export interface PurgeCacheOptions {
/**
* If true, purges only the transformations (resized/formatted variants) for the object or bucket,
* leaving the original cached file intact. If omitted, purges all cached versions.
* If true, purges only the transformations (resized/formatted variants) for the object, bucket
* or project, leaving the original cached files intact. If omitted, purges all cached versions.
*/
transformations?: true
}
Expand Down
68 changes: 68 additions & 0 deletions packages/core/storage-js/src/packages/StorageBucketApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,74 @@ export default class StorageBucketApi extends BaseApiClient<StorageError> {
})
}

/**
* Purges the CDN cache for every bucket in the project.
*
* Maps to `DELETE /cdn/` on the Storage API. The server issues a CDN
* invalidation for all objects in the project and returns `{ message: 'success' }`.
*
* **Requires the `service_role` key.** The underlying endpoint enforces
* `service_role` JWT — calls made with the anon key or a user JWT will be
* rejected by the server.
*
* **Hosted CDN feature.** On self-hosted Supabase, the Storage service must
* have `CDN_PURGE_ENDPOINT_URL` configured and the `purgeCache` tenant
* feature enabled, otherwise the server returns an error.
*
* To invalidate a single bucket or object instead, use
* {@link purgeBucketCache} or `from(bucket).purgeCache(path)`.
*
* @category Storage
* @subcategory File Buckets
* @param options Optional purge cache options.
* @param options.transformations If true, purges only transformations (resized/formatted variants), leaving original cached files intact.
* @param parameters Optional fetch parameters such as an `AbortController` signal.
* @returns Promise with `{ data: { message }, error: null }` on success or `{ data: null, error }` on failure.
*
* @example Purge cache for the entire project
* ```js
* const { data, error } = await supabase
* .storage
* .purgeProjectCache()
* ```
*
* @example Purge only transformations for the entire project
* ```js
* const { data, error } = await supabase
* .storage
* .purgeProjectCache({ transformations: true })
* ```
*/
async purgeProjectCache(
options?: PurgeCacheOptions,
parameters?: FetchParameters
): Promise<
| {
data: { message: string }
error: null
}
| {
data: null
error: StorageError
}
> {
return this.handleOperation(async () => {
const query = new URLSearchParams()
if (options?.transformations) {
query.set('transformations', 'true')
}
const queryString = query.toString()

return await remove(
this.fetch,
`${this.url}/cdn/${queryString ? `?${queryString}` : ''}`,
{},
{ headers: this.headers },
parameters
)
})
}

private bucketLifecycleUrl(id: string): string {
return `${this.url}/bucket/${encodeStoragePath(id)}/lifecycle`
}
Expand Down
91 changes: 91 additions & 0 deletions packages/core/storage-js/test/storageBucketApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,97 @@ describe('Bucket API Error Handling', () => {
})
})

describe('purgeProjectCache', () => {
const PURGE_URL = 'http://localhost:8000/storage/v1'

afterEach(() => {
jest.restoreAllMocks()
})

it('issues DELETE to /cdn/ and returns the server message', async () => {
const fetchMock = jest.fn().mockResolvedValue(
new Response(JSON.stringify({ message: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
)
global.fetch = fetchMock

const client = new StorageClient(PURGE_URL, { apikey: 'service-role-token' })
const { data, error } = await client.purgeProjectCache()

expect(error).toBeNull()
expect(data?.message).toBe('success')
expect(fetchMock).toHaveBeenCalledWith(
`${PURGE_URL}/cdn/`,
expect.objectContaining({ method: 'DELETE' })
)
})

it('surfaces server errors via StorageApiError', async () => {
const fetchMock = jest.fn().mockResolvedValue(
new Response(
JSON.stringify({
statusCode: '403',
error: 'Forbidden',
message: 'Feature not enabled',
}),
{ status: 403, headers: { 'Content-Type': 'application/json' } }
)
)
global.fetch = fetchMock

const client = new StorageClient(PURGE_URL, { apikey: 'service-role-token' })
const { data, error } = await client.purgeProjectCache()

expect(data).toBeNull()
expect(error).toBeInstanceOf(StorageApiError)
expect(error?.message).toBe('Feature not enabled')
})

it('appends transformations query param when transformations option is true', async () => {
const fetchMock = jest.fn().mockResolvedValue(
new Response(JSON.stringify({ message: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
)
global.fetch = fetchMock

const client = new StorageClient(PURGE_URL, { apikey: 'service-role-token' })
const { data, error } = await client.purgeProjectCache({ transformations: true })

expect(error).toBeNull()
expect(data?.message).toBe('success')
expect(fetchMock).toHaveBeenCalledWith(
`${PURGE_URL}/cdn/?transformations=true`,
expect.objectContaining({ method: 'DELETE' })
)
})

it('forwards the AbortController signal to fetch', async () => {
const fetchMock = jest.fn().mockResolvedValue(
new Response(JSON.stringify({ message: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
)
global.fetch = fetchMock

const client = new StorageClient(PURGE_URL, { apikey: 'service-role-token' })
const controller = new AbortController()
const { error } = await client.purgeProjectCache(undefined, {
signal: controller.signal,
})

expect(error).toBeNull()
expect(fetchMock).toHaveBeenCalledWith(
`${PURGE_URL}/cdn/`,
expect.objectContaining({ method: 'DELETE', signal: controller.signal })
)
})
})

describe('bucket lifecycle configuration', () => {
const LIFECYCLE_URL = 'http://localhost:8000/storage/v1'
const BUCKET = 'avatars'
Expand Down
5 changes: 5 additions & 0 deletions sdk-compliance.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -886,6 +886,11 @@ features:
status: implemented
symbols:
- default.purgeCache
storage.file_buckets.purge_project_cache:
status: implemented
symbols:
- default.purgeProjectCache
- StorageClient.purgeProjectCache
storage.file_buckets.remove:
status: implemented
symbols:
Expand Down