Skip to content

feat: add pagination to getAllBuckets #707

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

Merged
merged 6 commits into from
Jul 2, 2025
Merged
Show file tree
Hide file tree
Changes from 4 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
23 changes: 21 additions & 2 deletions src/http/routes/bucket/getAllBuckets.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { FastifyInstance } from 'fastify'
import { FromSchema } from 'json-schema-to-ts'
import { createDefaultSchema } from '../../routes-helper'
import { AuthenticatedRequest } from '../../types'
import { bucketSchema } from '@storage/schemas'
Expand All @@ -23,14 +24,30 @@ const successResponseSchema = {
],
}

const requestQuerySchema = {
type: 'object',
properties: {
limit: { type: 'integer', minimum: 1, examples: [10] },
offset: { type: 'integer', minimum: 1, examples: [1] },
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 offset min being 0 is fine. It's "useless" but a lot of time there will be code that sets a counter to 0 and increments it by limit per iteration and we shouldn't error if they pass in 0.

Also, I just checked listObjects and that is the behavior there so that would be consistent.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed 👍

sortColumn: { type: 'string', enum: ['id', 'name', 'created_at', 'updated_at'] },
sortOrder: { type: 'string', enum: ['asc', 'desc'] },
search: { type: 'string', examples: ["my-bucket"] }
},
} as const

interface GetAllBucketsRequest extends AuthenticatedRequest {
Querystring: FromSchema<typeof requestQuerySchema>
}

export default async function routes(fastify: FastifyInstance) {
const summary = 'Gets all buckets'
const schema = createDefaultSchema(successResponseSchema, {
querystring: requestQuerySchema,
summary,
tags: ['bucket'],
})

fastify.get<AuthenticatedRequest>(
fastify.get<GetAllBucketsRequest>(
'/',
{
schema,
Expand All @@ -39,8 +56,10 @@ export default async function routes(fastify: FastifyInstance) {
},
},
async (request, response) => {
const { limit, offset, sortColumn, sortOrder, search } = request.query
const results = await request.storage.listBuckets(
'id, name, public, owner, created_at, updated_at, file_size_limit, allowed_mime_types'
'id, name, public, owner, created_at, updated_at, file_size_limit, allowed_mime_types',
{ limit, offset, sortColumn, sortOrder, search }
)

return response.send(results)
Expand Down
10 changes: 9 additions & 1 deletion src/storage/database/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ export interface DatabaseOptions<TNX> {
parentConnection?: TenantConnection
}

export interface ListBucketOptions {
limit?: number
offset?: number
sortColumn?: string
sortOrder?: string
search?: string
}

export interface Database {
tenantHost: string
tenantId: string
Expand Down Expand Up @@ -108,7 +116,7 @@ export interface Database {
}
): Promise<S3MultipartUpload[]>

listBuckets(columns: string): Promise<Bucket[]>
listBuckets(columns: string, options?: ListBucketOptions): Promise<Bucket[]>
mustLockObject(bucketId: string, objectName: string, version?: string): Promise<boolean>
waitObjectLock(
bucketId: string,
Expand Down
23 changes: 21 additions & 2 deletions src/storage/database/knex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
FindBucketFilters,
FindObjectFilters,
SearchObjectOption,
ListBucketOptions,
} from './adapter'
import { DatabaseError } from 'pg'
import { getTenantConfig, TenantConnection } from '@internal/database'
Expand Down Expand Up @@ -283,9 +284,27 @@ export class StorageKnexDB implements Database {
})
}

async listBuckets(columns = 'id') {
async listBuckets(columns = 'id', options?: ListBucketOptions) {
const data = await this.runQuery('ListBuckets', (knex) => {
return knex.from<Bucket>('buckets').select(columns.split(','))
const query = knex.from<Bucket>('buckets').select(columns.split(','))

if (options?.search !== undefined) {
query.where('name', 'like', `${options.search}%`)
}

if (options?.sortColumn !== undefined) {
query.orderBy(options.sortColumn, options.sortOrder || 'asc')
}

if (options?.limit !== undefined) {
query.limit(options.limit)
}

if (options?.offset !== undefined) {
query.offset(options.offset)
}

return query
})

return data as Bucket[]
Expand Down
7 changes: 4 additions & 3 deletions src/storage/storage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { StorageBackendAdapter, withOptionalVersion } from './backend'
import { Database, FindBucketFilters } from './database'
import { Database, FindBucketFilters, ListBucketOptions } from './database'
import { ERRORS } from '@internal/errors'
import { AssetRenderer, HeadRenderer, ImageRenderer } from './renderer'
import { getFileSizeLimit, mustBeValidBucketName, parseFileSizeToBytes } from './limits'
Expand Down Expand Up @@ -68,9 +68,10 @@ export class Storage {
/**
* List buckets
* @param columns
* @param options
*/
listBuckets(columns = 'id') {
return this.db.listBuckets(columns)
listBuckets(columns = 'id', options?: ListBucketOptions) {
return this.db.listBuckets(columns, options)
}

/**
Expand Down
43 changes: 43 additions & 0 deletions src/test/bucket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,50 @@ describe('testing GET all buckets', () => {
})
expect(response.statusCode).toBe(400)
})

test('user is able to get buckets with limit, offset, search and sorting', async () => {
const response = await appInstance.inject({
method: 'GET',
url: `/bucket?limit=1&offset=2&sortColumn=name&sortOrder=asc&search=bucket`,
headers: {
authorization: `Bearer ${process.env.AUTHENTICATED_KEY}`,
},
})
expect(response.statusCode).toBe(200)
const responseJSON = JSON.parse(response.body)
expect(responseJSON.length).toEqual(1)
expect(responseJSON[0]).toMatchObject({
id: 'bucket4',
name: 'bucket4',
public: false,
file_size_limit: null,
allowed_mime_types: null,
})
})

test('limit=0 returns 400', async () => {
const response = await appInstance.inject({
method: 'GET',
url: `/bucket?limit=0`,
headers: {
authorization: `Bearer ${process.env.AUTHENTICATED_KEY}`,
},
})
expect(response.statusCode).toBe(400)
})

test('offset=0 returns 400', async () => {
const response = await appInstance.inject({
method: 'GET',
url: `/bucket?offset=0`,
headers: {
authorization: `Bearer ${process.env.AUTHENTICATED_KEY}`,
},
})
expect(response.statusCode).toBe(400)
})
})

/*
* POST /bucket
*/
Expand Down
Loading