Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(api): add sorting to document list endpoint (#1089)

Corentin Thomassetaef3ef276c98
diff --git a/.changeset/sorting-route-params.md b/.changeset/sorting-route-params.md
new file mode 100644
index 00000000..adc03b1d
--- /dev/null
+++ b/.changeset/sorting-route-params.md
@@ -0,0 +1,5 @@
+---
+"@papra/app": patch
+---
+
+Added `sortField` and `sortOrder` query parameters to the document list/search endpoint (`GET /api/organizations/:organizationId/documents`), allowing documents to be sorted by `createdAt`, `updatedAt`, `name`, or `documentDate` in ascending or descending order.
diff --git a/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx b/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx
index 4b4b40ac..b7cf970e 100644
--- a/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx
+++ b/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx
@@ -156,6 +156,8 @@ List all documents in the organization.
- `pageIndex`: (optional, default: 0) The page index to start from.
- `pageSize`: (optional, default: 100) The number of documents to return.
- `searchQuery`: (optional) Search query, can reference [Filters](https://docs.papra.app/guides/advanced-search/#filters) for a more defined search
+ - `sortField`: (optional, default: `createdAt`) Field to sort by, one of `createdAt`, `updatedAt`, `name`, `documentDate`.
+ - `sortOrder`: (optional, default: `desc`) Sort direction, one of `asc`, `desc`.
- Response (JSON)
- `documents`: The list of documents.
- `documentsCount`: The total number of documents.
diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.ts
index 697eb815..8c93923d 100644
--- a/apps/papra-server/src/modules/documents/documents.routes.ts
+++ b/apps/papra-server/src/modules/documents/documents.routes.ts
@@ -14,11 +14,12 @@ import { getFileStreamFromMultipartForm } from '../shared/streams/file-upload';
import { validateJsonBody, validateParams, validateQuery } from '../shared/validation/validation';
import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';
import { createTagsRepository } from '../tags/tags.repository';
+import { DEFAULT_DOCUMENT_SEARCH_SORT } from './document-search/document-search.constants';
import { searchOrganizationDocuments } from './document-search/document-search.usecase';
import { createDocumentIsNotDeletedError } from './documents.errors';
import { formatDocumentForApi, formatDocumentsForApi, isDocumentSizeLimitEnabled } from './documents.models';
import { createDocumentsRepository } from './documents.repository';
-import { documentIdSchema, searchDocumentsQuerySchema, updateDocumentBodySchema } from './documents.schemas';
+import { documentIdSchema, documentSearchSortFieldSchema, documentSearchSortOrderSchema, searchDocumentsQuerySchema, updateDocumentBodySchema } from './documents.schemas';
import { createDocumentCreationUsecase, deleteAllTrashDocuments, deleteTrashDocument, enrichAndFormatDocumentForApi, enrichAndFormatDocumentsForApi, ensureDocumentExists, getDocumentOrThrow, restoreDocument, trashDocument, updateDocument } from './documents.usecases';
export function registerDocumentsRoutes(context: RouteDefinitionContext) {
@@ -265,6 +266,8 @@ function setupGetDocumentsRoute({ app, db, documentSearchServices }: RouteDefini
validateQuery(
v.strictObject({
searchQuery: v.optional(searchDocumentsQuerySchema, ''),
+ sortField: v.optional(documentSearchSortFieldSchema, DEFAULT_DOCUMENT_SEARCH_SORT.field),
+ sortOrder: v.optional(documentSearchSortOrderSchema, DEFAULT_DOCUMENT_SEARCH_SORT.order),
...createQueryPaginationSchemaKeys({ maxPageSize: 100, defaultPageSize: 100 }),
}),
),
@@ -272,7 +275,7 @@ function setupGetDocumentsRoute({ app, db, documentSearchServices }: RouteDefini
const { userId } = getUser({ context });
const { organizationId } = context.req.valid('param');
- const { searchQuery, pageIndex, pageSize } = context.req.valid('query');
+ const { searchQuery, pageIndex, pageSize, sortField, sortOrder } = context.req.valid('query');
const organizationsRepository = createOrganizationsRepository({ db });
const customPropertiesRepository = createCustomPropertiesRepository({ db });
@@ -280,7 +283,7 @@ function setupGetDocumentsRoute({ app, db, documentSearchServices }: RouteDefini
await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
- const { documents, documentsCount } = await searchOrganizationDocuments({ organizationId, searchQuery, pageIndex, pageSize, documentSearchServices });
+ const { documents, documentsCount } = await searchOrganizationDocuments({ organizationId, searchQuery, pageIndex, pageSize, sort: { field: sortField, order: sortOrder }, documentSearchServices });
const { enrichedDocuments } = await enrichAndFormatDocumentsForApi({ documents, tagsRepository, customPropertiesRepository });
return context.json({ documents: enrichedDocuments, documentsCount });
diff --git a/apps/papra-server/src/modules/documents/documents.schemas.ts b/apps/papra-server/src/modules/documents/documents.schemas.ts
index 9624e12a..5a21ccf3 100644
--- a/apps/papra-server/src/modules/documents/documents.schemas.ts
+++ b/apps/papra-server/src/modules/documents/documents.schemas.ts
@@ -1,5 +1,6 @@
import * as v from 'valibot';
import { createRegexSchema } from '../shared/schemas/string.schemas';
+import { documentSearchSortFields, documentSearchSortOrders } from './document-search/document-search.constants';
import { DOCUMENT_ID_REGEX, OCR_LANGUAGES } from './documents.constants';
export const documentIdSchema = createRegexSchema(DOCUMENT_ID_REGEX);
@@ -24,3 +25,6 @@ export const stringCoercedOcrLanguagesSchema = v.pipe(
);
export const searchDocumentsQuerySchema = v.pipe(v.string(), v.maxLength(1024));
+
+export const documentSearchSortFieldSchema = v.picklist(documentSearchSortFields);
+export const documentSearchSortOrderSchema = v.picklist(documentSearchSortOrders);
diff --git a/apps/papra-server/src/modules/documents/e2e/list-documents-sorting.e2e.test.ts b/apps/papra-server/src/modules/documents/e2e/list-documents-sorting.e2e.test.ts
new file mode 100644
index 00000000..9b7241c3
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/e2e/list-documents-sorting.e2e.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../../app/database/database.test-utils';
+import { createServer } from '../../app/server';
+import { createTestServerDependencies } from '../../app/server.test-utils';
+import { overrideConfig } from '../../config/config.test-utils';
+import { ORGANIZATION_ROLES } from '../../organizations/organizations.constants';
+
+const USER_ID = 'usr_111111111111111111111111';
+const ORGANIZATION_ID = 'org_222222222222222222222222';
+
+function makeDocument({ id, name, createdAt }: { id: string; name: string; createdAt: Date }) {
+ return {
+ id,
+ name,
+ content: '',
+ organizationId: ORGANIZATION_ID,
+ mimeType: 'text/plain',
+ originalName: name,
+ createdAt,
+ updatedAt: createdAt,
+ createdBy: USER_ID,
+ originalStorageKey: `documents/${id}`,
+ originalSha256Hash: `hash${id}`,
+ isDeleted: false,
+ };
+}
+
+async function listDocuments({ query = '' }: { query?: string } = {}) {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: USER_ID, email: '[email protected]' }],
+ organizations: [{ id: ORGANIZATION_ID, name: 'Org 1' }],
+ organizationMembers: [{ organizationId: ORGANIZATION_ID, userId: USER_ID, role: ORGANIZATION_ROLES.OWNER }],
+ documents: [
+ makeDocument({ id: 'doc_111111111111111111111111', name: 'banana.txt', createdAt: new Date('2026-01-03') }),
+ makeDocument({ id: 'doc_222222222222222222222222', name: 'apple.txt', createdAt: new Date('2026-01-01') }),
+ makeDocument({ id: 'doc_333333333333333333333333', name: 'Cherry.txt', createdAt: new Date('2026-01-02') }),
+ ],
+ });
+
+ const { app } = createServer(createTestServerDependencies({
+ db,
+ config: overrideConfig({ env: 'test' }),
+ }));
+
+ const response = await app.request(
+ `/api/organizations/${ORGANIZATION_ID}/documents${query}`,
+ {},
+ { loggedInUserId: USER_ID },
+ );
+
+ const body = response.status === 200
+ ? (await response.json()) as { documents: { name: string }[]; documentsCount: number }
+ : undefined;
+
+ return { status: response.status, documentNames: body?.documents.map(document => document.name) };
+}
+
+describe('documents e2e', () => {
+ describe('list documents sorting', () => {
+ test('documents are sorted by creation date, most recent first, by default', async () => {
+ const { status, documentNames } = await listDocuments();
+
+ expect(status).to.eql(200);
+ expect(documentNames).to.eql(['banana.txt', 'Cherry.txt', 'apple.txt']);
+ });
+
+ test('documents can be sorted by name ascending, case-insensitively', async () => {
+ const { status, documentNames } = await listDocuments({ query: '?sortField=name&sortOrder=asc' });
+
+ expect(status).to.eql(200);
+ expect(documentNames).to.eql(['apple.txt', 'banana.txt', 'Cherry.txt']);
+ });
+
+ test('documents can be sorted by name descending', async () => {
+ const { status, documentNames } = await listDocuments({ query: '?sortField=name&sortOrder=desc' });
+
+ expect(status).to.eql(200);
+ expect(documentNames).to.eql(['Cherry.txt', 'banana.txt', 'apple.txt']);
+ });
+
+ test('an unknown sort field is rejected', async () => {
+ const { status } = await listDocuments({ query: '?sortField=size' });
+
+ expect(status).to.eql(400);
+ });
+ });
+});