Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

refactor(search): mutualize the document search in adapter pattern (#650)

Corentin Thomassetdc6ee5b22877
diff --git a/.changeset/chubby-cases-float.md b/.changeset/chubby-cases-float.md
new file mode 100644
index 00000000..96597a40
--- /dev/null
+++ b/.changeset/chubby-cases-float.md
@@ -0,0 +1,31 @@
+---
+"@papra/docker": patch
+---
+
+Api breaking change: the document search endpoint return format changed, impacting any custom clients consuming it.
+
+Before
+
+```ts
+// Get /api/organizations/:organizationId/documents/search
+{
+ documents: {
+ id: string;
+ name: string;
+ mimeType: string;
+ // ... other document fields
+ }[]
+}
+```
+
+After
+
+```ts
+// Get /api/organizations/:organizationId/documents/search
+{
+ searchResults: {
+ documents: { id: string; name: string }[]
+ }
+}
+```
+
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 dd15b254..1b387cea 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
@@ -201,7 +201,10 @@ Search documents in the organization by name or content.
- `pageIndex`: (optional, default: 0) The page index to start from.
- `pageSize`: (optional, default: 100) The number of documents to return.
- Response (JSON)
- - `documents`: The list of documents.
+ - `searchResults`: The search results.
+ - `documents`: The list of matching documents.
+ - `id`: The document ID.
+ - `name`: The document name.
### Get organization documents statistics
diff --git a/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx b/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx
index d615c3f1..551e6a9c 100644
--- a/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx
+++ b/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx
@@ -1,5 +1,4 @@
import type { Accessor, ParentComponent } from 'solid-js';
-import type { Document } from '../documents/documents.types';
import { safely } from '@corentinth/chisels';
import { useNavigate, useParams } from '@solidjs/router';
import { createContext, createEffect, createSignal, For, on, onCleanup, onMount, Show, useContext } from 'solid-js';
@@ -29,7 +28,7 @@ export function useCommandPalette() {
export const CommandPaletteProvider: ParentComponent = (props) => {
const [getIsCommandPaletteOpen, setIsCommandPaletteOpen] = createSignal(false);
- const [getMatchingDocuments, setMatchingDocuments] = createSignal<Document[]>([]);
+ const [getMatchingDocuments, setMatchingDocuments] = createSignal<{ id: string; name: string }[]>([]);
const [getSearchQuery, setSearchQuery] = createSignal('');
const [getIsLoading, setIsLoading] = createSignal(false);
@@ -57,9 +56,7 @@ export const CommandPaletteProvider: ParentComponent = (props) => {
const searchDocs = debounce(async ({ searchQuery }: { searchQuery: string }) => {
const [result] = await safely(searchDocuments({ searchQuery, organizationId: params.organizationId, pageIndex: 0, pageSize: 5 }));
- const { documents = [] } = result ?? {};
-
- setMatchingDocuments(documents);
+ setMatchingDocuments(result?.searchResults.documents ?? []);
setIsLoading(false);
}, 300);
diff --git a/apps/papra-client/src/modules/demo/demo-api-mock.ts b/apps/papra-client/src/modules/demo/demo-api-mock.ts
index 3de2948e..eb2c6636 100644
--- a/apps/papra-client/src/modules/demo/demo-api-mock.ts
+++ b/apps/papra-client/src/modules/demo/demo-api-mock.ts
@@ -211,8 +211,11 @@ const inMemoryApiMock: Record<string, { handler: any }> = {
const filteredDocuments = documents.filter(matchQuery);
return {
- documents: filteredDocuments.slice(pageIndex * pageSize, (pageIndex + 1) * pageSize),
- documentsCount: filteredDocuments.length,
+ searchResults: {
+ documents: filteredDocuments
+ .slice(pageIndex * pageSize, (pageIndex + 1) * pageSize)
+ .map(({ id, name }) => ({ id, name })),
+ },
};
},
}),
diff --git a/apps/papra-client/src/modules/documents/document.models.test.ts b/apps/papra-client/src/modules/documents/document.models.test.ts
index 6d8a5b06..28ed64f1 100644
--- a/apps/papra-client/src/modules/documents/document.models.test.ts
+++ b/apps/papra-client/src/modules/documents/document.models.test.ts
@@ -1,79 +1,122 @@
import { icons as tablerIconSet } from '@iconify-json/tabler';
import { describe, expect, test } from 'vitest';
-import { getDaysBeforePermanentDeletion, getDocumentIcon, getDocumentNameExtension, getDocumentNameWithoutExtension, iconByFileType } from './document.models';
+import { fileIcons, getDaysBeforePermanentDeletion, getDocumentIcon, getDocumentNameExtension, getDocumentNameWithoutExtension } from './document.models';
describe('files models', () => {
describe('iconByFileType', () => {
- const icons = Object.values(iconByFileType);
-
- test('they must at least have the default icon', () => {
- expect(iconByFileType['*']).toBeDefined();
- });
-
test('all the icons should be from tabler icon set', () => {
- for (const icon of icons) {
+ for (const { icon } of fileIcons) {
expect(icon).to.match(/^i-tabler-/, `Icon ${icon} is not from tabler icon set`);
}
});
test('icons should not contain any spaces', () => {
- for (const icon of icons) {
+ for (const { icon } of fileIcons) {
expect(icon).not.to.match(/\s/, `Icon ${icon} contains spaces`);
}
});
test('the icons used for showing file types should exists with current iconify configuration', () => {
- for (const icon of icons) {
+ for (const { icon } of fileIcons) {
const iconName = icon.replace('i-tabler-', '');
const iconData = tablerIconSet.icons[iconName] ?? tablerIconSet.aliases?.[iconName];
expect(iconData).to.not.eql(undefined, `Icon ${icon} does not exist in tabler icon set`);
}
});
+
+ test('there should not be duplicate icons for a file extension', () => {
+ const seenExtensions = new Set<string>();
+
+ for (const { extensions, icon } of fileIcons) {
+ for (const extension of extensions) {
+ expect(
+ seenExtensions.has(extension),
+ ).to.eql(
+ false,
+ `Duplicate icon ${icon} found for extension .${extension}`,
+ );
+ seenExtensions.add(extension);
+ }
+ }
+ });
+
+ test('there should not be duplicate icons for a mime type', () => {
+ const seenMimeTypes = new Set<string>();
+
+ for (const { mimeTypes, icon } of fileIcons) {
+ for (const mimeType of mimeTypes) {
+ expect(
+ seenMimeTypes.has(mimeType),
+ ).to.eql(
+ false,
+ `Duplicate icon ${icon} found for mime type ${mimeType}`,
+ );
+ seenMimeTypes.add(mimeType);
+ }
+ }
+ });
});
describe('getFileIcon', () => {
test('a file icon is selected based on the file type', () => {
const document = { mimeType: 'text/plain' };
- const iconsMap = {
- '*': 'i-tabler-file',
- 'text/plain': 'i-tabler-file-text',
- };
- const icon = getDocumentIcon({ document, iconsMap });
+
+ const icon = getDocumentIcon({ document });
expect(icon).to.eql('i-tabler-file-text');
});
test('if a file type is not associated with an icon, the default icon is used', () => {
- const document = { mimeType: 'text/html' };
- const iconsMap = {
- '*': 'i-tabler-file',
- 'text/plain': 'i-tabler-file-text',
- };
- const icon = getDocumentIcon({ document, iconsMap });
+ const document = { mimeType: 'foo/bar' };
+
+ const icon = getDocumentIcon({ document });
expect(icon).to.eql('i-tabler-file');
});
test('a file icon can be selected based on the file type group', () => {
- const document = { mimeType: 'text/html' };
- const iconsMap = {
- '*': 'i-tabler-file',
- 'text': 'i-tabler-file-text',
- };
- const icon = getDocumentIcon({ document, iconsMap });
+ const document = { mimeType: 'image/unknow-image-format' };
- expect(icon).to.eql('i-tabler-file-text');
+ const icon = getDocumentIcon({ document });
+
+ expect(icon).to.eql('i-tabler-photo');
});
test('when an icon is defined for both the whole type and the group type, the file type icon is used', () => {
const document = { mimeType: 'text/html' };
- const iconsMap = {
- '*': 'i-tabler-file',
- 'text': 'i-tabler-file-text',
- 'text/html': 'i-tabler-file-type-html',
- };
- const icon = getDocumentIcon({ document, iconsMap });
+ const icon = getDocumentIcon({ document, iconByMimeTypeMap: { 'text/html': 'i-tabler-file-type-html', 'text': 'i-tabler-file-text' } });
+
+ expect(icon).to.eql('i-tabler-file-type-html');
+ });
+
+ test('a file icon can be selected based on the file extension', () => {
+ const document = { name: 'document.css' };
+
+ const icon = getDocumentIcon({ document });
+
+ expect(icon).to.eql('i-tabler-file-type-css');
+ });
+
+ test('if no file type or extension match is found, the default icon is used', () => {
+ const document = { name: 'document.unknownextension' };
+
+ const icon = getDocumentIcon({ document });
+
+ expect(icon).to.eql('i-tabler-file');
+ });
+
+ test('if the document has no name nor mimeType, the default icon is used', () => {
+ expect(getDocumentIcon({ document: { name: undefined, mimeType: undefined } })).to.eql('i-tabler-file');
+ expect(getDocumentIcon({ document: { name: undefined } })).to.eql('i-tabler-file');
+ expect(getDocumentIcon({ document: { mimeType: undefined } })).to.eql('i-tabler-file');
+ expect(getDocumentIcon({ document: { } })).to.eql('i-tabler-file');
+ });
+
+ test('when a document has both a mimeType and a name, the mimeType takes precedence for icon selection', () => {
+ const document = { name: 'document.css', mimeType: 'text/html' };
+
+ const icon = getDocumentIcon({ document });
expect(icon).to.eql('i-tabler-file-type-html');
});
diff --git a/apps/papra-client/src/modules/documents/document.models.ts b/apps/papra-client/src/modules/documents/document.models.ts
index 4d859f89..302b16a8 100644
--- a/apps/papra-client/src/modules/documents/document.models.ts
+++ b/apps/papra-client/src/modules/documents/document.models.ts
@@ -1,42 +1,122 @@
import type { DocumentActivityEvent } from './documents.types';
import { IN_MS } from '../shared/utils/units';
-export const iconByFileType = {
- '*': 'i-tabler-file',
- 'image': 'i-tabler-photo',
- 'video': 'i-tabler-video',
- 'audio': 'i-tabler-file-music',
- 'application': 'i-tabler-file-code',
- 'application/pdf': 'i-tabler-file-type-pdf',
- 'application/zip': 'i-tabler-file-zip',
- 'application/vnd.ms-excel': 'i-tabler-file-excel',
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'i-tabler-file-excel',
- 'application/msword': 'i-tabler-file-word',
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'i-tabler-file-word',
- 'application/json': 'i-tabler-file-code',
- 'application/xml': 'i-tabler-file-code',
- 'application/javascript': 'i-tabler-file-type-js',
- 'application/typescript': 'i-tabler-file-type-ts',
- 'application/vnd.ms-powerpoint': 'i-tabler-file-type-ppt',
- 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'i-tabler-file-type-ppt',
- 'text/plain': 'i-tabler-file-text',
- 'text/html': 'i-tabler-file-type-html',
- 'text/css': 'i-tabler-file-type-css',
- 'text/csv': 'i-tabler-file-type-csv',
- 'text/xml': 'i-tabler-file-type-xml',
- 'text/javascript': 'i-tabler-file-type-js',
- 'text/typescript': 'i-tabler-file-type-ts',
-};
-
-type FileTypes = keyof typeof iconByFileType;
-
-export function getDocumentIcon({ document, iconsMap = iconByFileType }: { document: { mimeType: string }; iconsMap?: Record<string, string> & { '*': string } }): string {
- const { mimeType } = document;
- const fileTypeGroup = mimeType?.split('/')[0];
-
- const icon = iconsMap[mimeType as FileTypes] ?? iconsMap[fileTypeGroup as FileTypes] ?? iconsMap['*'];
-
- return icon;
+export const fileIcons: { mimeTypes: string[]; extensions: string[]; icon: string }[] = [
+ {
+ mimeTypes: ['image'],
+ extensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp', 'tiff', 'heic'],
+ icon: 'i-tabler-photo',
+ },
+ {
+ mimeTypes: ['video'],
+ extensions: ['mp4', 'mov', 'avi', 'mkv', 'wmv', 'flv', 'webm'],
+ icon: 'i-tabler-video',
+ },
+ {
+ mimeTypes: ['audio'],
+ extensions: ['mp3', 'wav', 'ogg', 'flac', 'aac'],
+ icon: 'i-tabler-file-music',
+ },
+ {
+ mimeTypes: ['application/pdf'],
+ extensions: ['pdf'],
+ icon: 'i-tabler-file-type-pdf',
+ },
+ {
+ mimeTypes: ['application/zip', 'application/x-rar-compressed', 'application/x-7z-compressed'],
+ extensions: ['zip', 'rar', '7z'],
+ icon: 'i-tabler-file-zip',
+ },
+ {
+ mimeTypes: ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
+ extensions: ['xls', 'xlsx'],
+ icon: 'i-tabler-file-excel',
+ },
+ {
+ mimeTypes: ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
+ extensions: ['doc', 'docx'],
+ icon: 'i-tabler-file-word',
+ },
+ {
+ mimeTypes: ['application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
+ extensions: ['ppt', 'pptx'],
+ icon: 'i-tabler-file-type-ppt',
+ },
+ {
+ mimeTypes: ['text/plain'],
+ extensions: ['txt', 'md', 'rtf'],
+ icon: 'i-tabler-file-text',
+ },
+ {
+ mimeTypes: ['application/json', 'application/xml', 'application/javascript', 'application/typescript', 'text/xml', 'text/javascript', 'text/typescript'],
+ extensions: ['json', 'xml', 'js', 'ts'],
+ icon: 'i-tabler-file-code',
+ },
+ {
+ mimeTypes: ['text/html'],
+ extensions: ['html', 'htm'],
+ icon: 'i-tabler-file-type-html',
+ },
+ {
+ mimeTypes: ['text/css'],
+ extensions: ['css'],
+ icon: 'i-tabler-file-type-css',
+ },
+ {
+ mimeTypes: ['text/csv'],
+ extensions: ['csv'],
+ icon: 'i-tabler-file-type-csv',
+ },
+];
+
+// Indexed the icons by mime type and extension for quick lookup
+export const { iconByExtension, iconByFileType } = fileIcons.reduce(
+ ({ iconByFileType, iconByExtension }, { mimeTypes, extensions, icon }) => ({
+ iconByFileType: {
+ ...iconByFileType,
+ ...Object.fromEntries(mimeTypes.map(mimeType => [mimeType, icon])),
+ },
+ iconByExtension: {
+ ...iconByExtension,
+ ...Object.fromEntries(extensions.map(extension => [extension, icon])),
+ },
+ }),
+ { iconByFileType: {} as Record<string, string>, iconByExtension: {} as Record<string, string> },
+);
+
+export function getDocumentIcon({
+ document,
+ iconByMimeTypeMap = iconByFileType,
+ iconByExtensionMap = iconByExtension,
+ defaultIcon = 'i-tabler-file',
+}: { document: {
+ mimeType?: string;
+ name?: string;
+}; iconByMimeTypeMap?: Record<string, string>; iconByExtensionMap?: Record<string, string>; defaultIcon?: string; }): string {
+ const { mimeType, name } = document;
+
+ const mimeTypeIcon = mimeType ? iconByMimeTypeMap[mimeType] : undefined;
+ if (mimeTypeIcon) {
+ return mimeTypeIcon;
+ }
+
+ const mimeTypeGroup = mimeType?.split('/')[0];
+ const mimeTypeGroupIcon = mimeTypeGroup ? iconByMimeTypeMap[mimeTypeGroup] : undefined;
+ if (mimeTypeGroupIcon) {
+ return mimeTypeGroupIcon;
+ }
+
+ if (!name || !name.includes('.')) {
+ return defaultIcon;
+ }
+
+ const extension = getDocumentNameExtension({ name });
+ const extensionIcon = extension ? iconByExtensionMap[extension] : undefined;
+ if (extensionIcon) {
+ return extensionIcon;
+ }
+
+ return defaultIcon;
}
export function getDaysBeforePermanentDeletion({ document, deletedDocumentsRetentionDays, now = new Date() }: { document: { deletedAt?: Date }; deletedDocumentsRetentionDays: number; now?: Date }) {
diff --git a/apps/papra-client/src/modules/documents/documents.services.ts b/apps/papra-client/src/modules/documents/documents.services.ts
index c4b73300..62124c98 100644
--- a/apps/papra-client/src/modules/documents/documents.services.ts
+++ b/apps/papra-client/src/modules/documents/documents.services.ts
@@ -151,8 +151,8 @@ export async function searchDocuments({
pageSize: number;
}) {
const {
- documents,
- } = await apiClient<{ documents: AsDto<Document>[] }>({
+ searchResults,
+ } = await apiClient<{ searchResults: { documents: { id: string; name: string }[] } }>({
method: 'GET',
path: `/api/organizations/${organizationId}/documents/search`,
query: {
@@ -163,7 +163,7 @@ export async function searchDocuments({
});
return {
- documents: documents.map(coerceDates),
+ searchResults,
};
}
diff --git a/apps/papra-client/uno.config.ts b/apps/papra-client/uno.config.ts
index bf64fa8c..3711cca3 100644
--- a/apps/papra-client/uno.config.ts
+++ b/apps/papra-client/uno.config.ts
@@ -8,7 +8,7 @@ import {
} from 'unocss';
import { presetAnimations } from 'unocss-preset-animations';
import { ssoProviders } from './src/modules/auth/auth.constants';
-import { documentActivityIcon, iconByFileType } from './src/modules/documents/document.models';
+import { documentActivityIcon, fileIcons } from './src/modules/documents/document.models';
export default defineConfig({
presets: [
@@ -116,9 +116,9 @@ export default defineConfig({
},
safelist: [
...new Set([
- ...Object.values(iconByFileType),
+ ...fileIcons.map(({ icon }) => icon),
...Object.values(documentActivityIcon),
- ...(ssoProviders.map(p => p.icon)),
+ ...ssoProviders.map(({ icon }) => icon),
]),
],
});
diff --git a/apps/papra-server/src/modules/app/server.ts b/apps/papra-server/src/modules/app/server.ts
index edb3cfdc..0aa38aa1 100644
--- a/apps/papra-server/src/modules/app/server.ts
+++ b/apps/papra-server/src/modules/app/server.ts
@@ -3,6 +3,7 @@ import { Hono } from 'hono';
import { secureHeaders } from 'hono/secure-headers';
import { createApiKeyMiddleware } from '../api-keys/api-keys.middlewares';
import { parseConfig } from '../config/config';
+import { createDocumentSearchServices } from '../documents/document-search/document-search.registry';
import { createDocumentStorageService } from '../documents/storage/documents.storage.services';
import { createEmailsServices } from '../emails/emails.services';
import { createLoggerMiddleware } from '../shared/logger/logger.middleware';
@@ -27,6 +28,7 @@ async function createGlobalDependencies(partialDeps: Partial<GlobalDependencies>
const subscriptionsServices = createSubscriptionsServices({ config });
const taskServices = partialDeps.taskServices ?? createTaskServices({ config });
const documentsStorageService = partialDeps.documentsStorageService ?? createDocumentStorageService({ documentStorageConfig: config.documentsStorage });
+ const documentSearchServices = partialDeps.documentSearchServices ?? createDocumentSearchServices({ db, config });
return {
documentsStorageService,
@@ -37,6 +39,7 @@ async function createGlobalDependencies(partialDeps: Partial<GlobalDependencies>
subscriptionsServices,
trackingServices,
taskServices,
+ documentSearchServices,
};
}
diff --git a/apps/papra-server/src/modules/app/server.types.ts b/apps/papra-server/src/modules/app/server.types.ts
index 1f666801..62ee6581 100644
--- a/apps/papra-server/src/modules/app/server.types.ts
+++ b/apps/papra-server/src/modules/app/server.types.ts
@@ -1,6 +1,7 @@
import type { Context as BaseContext, Hono } from 'hono';
import type { ApiKey } from '../api-keys/api-keys.types';
import type { Config } from '../config/config.types';
+import type { DocumentSearchServices } from '../documents/document-search/document-search.types';
import type { DocumentStorageService } from '../documents/storage/documents.storage.services';
import type { EmailsServices } from '../emails/emails.services';
import type { SubscriptionsServices } from '../subscriptions/subscriptions.services';
@@ -32,6 +33,7 @@ export type GlobalDependencies = {
trackingServices: TrackingServices;
taskServices: TaskServices;
documentsStorageService: DocumentStorageService;
+ documentSearchServices: DocumentSearchServices;
};
export type RouteDefinitionContext = { app: ServerInstance } & GlobalDependencies;
diff --git a/apps/papra-server/src/modules/config/config.ts b/apps/papra-server/src/modules/config/config.ts
index 4ad541e6..a8547a9b 100644
--- a/apps/papra-server/src/modules/config/config.ts
+++ b/apps/papra-server/src/modules/config/config.ts
@@ -7,6 +7,7 @@ import { memoize } from 'lodash-es';
import { z } from 'zod';
import { authConfig } from '../app/auth/auth.config';
import { databaseConfig } from '../app/database/database.config';
+import { documentSearchConfig } from '../documents/document-search/document-search.config';
import { documentsConfig } from '../documents/documents.config';
import { documentStorageConfig } from '../documents/storage/document-storage.config';
import { emailsConfig } from '../emails/emails.config';
@@ -108,6 +109,7 @@ export const configDefinition = {
database: databaseConfig,
documents: documentsConfig,
documentsStorage: documentStorageConfig,
+ documentSearch: documentSearchConfig,
auth: authConfig,
ingestionFolder: ingestionFolderConfig,
tasks: tasksConfig,
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.document-search-provider.constants.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.document-search-provider.constants.ts
new file mode 100644
index 00000000..9dbbc2eb
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.document-search-provider.constants.ts
@@ -0,0 +1 @@
+export const DATABASE_FTS5_DOCUMENT_SEARCH_PROVIDER_NAME = 'database-fts5' as const;
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.document-search-provider.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.document-search-provider.ts
new file mode 100644
index 00000000..fe5808d2
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.document-search-provider.ts
@@ -0,0 +1,21 @@
+import type { Database } from '../../../app/database/database.types';
+import type { DocumentSearchServices } from '../document-search.types';
+import { createDocumentsRepository } from '../../documents.repository';
+import { DATABASE_FTS5_DOCUMENT_SEARCH_PROVIDER_NAME } from './database-fts5.document-search-provider.constants';
+
+export function createDatabaseFts5DocumentSearchServices({ db }: { db: Database }): DocumentSearchServices {
+ const documentsRepository = createDocumentsRepository({ db });
+
+ return {
+ name: DATABASE_FTS5_DOCUMENT_SEARCH_PROVIDER_NAME,
+ searchDocuments: async ({ searchQuery, organizationId, pageIndex, pageSize }) => {
+ const { documents } = await documentsRepository.searchOrganizationDocuments({ organizationId, searchQuery, pageIndex, pageSize });
+
+ return {
+ searchResults: {
+ documents: documents.map(({ id, name }) => ({ id, name })),
+ },
+ };
+ },
+ };
+}
diff --git a/apps/papra-server/src/modules/documents/document-search/document-search.config.ts b/apps/papra-server/src/modules/documents/document-search/document-search.config.ts
new file mode 100644
index 00000000..d54dee65
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/document-search.config.ts
@@ -0,0 +1,14 @@
+import type { ConfigDefinition } from 'figue';
+import { z } from 'zod';
+import { DATABASE_FTS5_DOCUMENT_SEARCH_PROVIDER_NAME } from './database-fts5/database-fts5.document-search-provider.constants';
+
+const documentSearchProviderNames = [DATABASE_FTS5_DOCUMENT_SEARCH_PROVIDER_NAME] as const;
+
+export const documentSearchConfig = {
+ providerName: {
+ doc: `The document search provider to use, values can be one of: ${documentSearchProviderNames.map(x => `\`${x}\``).join(', ')}`,
+ default: DATABASE_FTS5_DOCUMENT_SEARCH_PROVIDER_NAME,
+ env: 'DOCUMENT_SEARCH_DRIVER',
+ schema: z.enum(documentSearchProviderNames),
+ },
+} as const satisfies ConfigDefinition;
diff --git a/apps/papra-server/src/modules/documents/document-search/document-search.registry.ts b/apps/papra-server/src/modules/documents/document-search/document-search.registry.ts
new file mode 100644
index 00000000..f9041754
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/document-search.registry.ts
@@ -0,0 +1,35 @@
+import type { Config } from '../../config/config.types';
+import { createError } from '../../shared/errors/errors';
+import { isNil } from '../../shared/utils';
+import { createDatabaseFts5DocumentSearchServices } from './database-fts5/database-fts5.document-search-provider';
+import { DATABASE_FTS5_DOCUMENT_SEARCH_PROVIDER_NAME } from './database-fts5/database-fts5.document-search-provider.constants';
+
+const searchServicesFactories = {
+ [DATABASE_FTS5_DOCUMENT_SEARCH_PROVIDER_NAME]: createDatabaseFts5DocumentSearchServices,
+};
+
+type DocumentsSearchFactoriesArgs = {
+ [K in keyof typeof searchServicesFactories]: Parameters<typeof searchServicesFactories[K]>[0];
+}[keyof typeof searchServicesFactories];
+
+export function createDocumentSearchServices({
+ config,
+ ...args
+}: {
+ config: Config;
+} & DocumentsSearchFactoriesArgs) {
+ const { providerName } = config.documentSearch;
+
+ const searchServicesFactory = searchServicesFactories[providerName];
+
+ if (isNil(searchServicesFactory)) {
+ throw createError({
+ message: `Unknown document search provider: ${providerName}`,
+ code: 'document_search_provider.unknown_provider',
+ isInternal: true,
+ statusCode: 500,
+ });
+ }
+
+ return searchServicesFactory({ ...args });
+}
diff --git a/apps/papra-server/src/modules/documents/document-search/document-search.types.ts b/apps/papra-server/src/modules/documents/document-search/document-search.types.ts
new file mode 100644
index 00000000..e51c408f
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/document-search.types.ts
@@ -0,0 +1,9 @@
+export type DocumentSearchServices = {
+ name: string;
+ searchDocuments: (args: {
+ searchQuery: string;
+ organizationId: string;
+ pageIndex: number;
+ pageSize: number;
+ }) => Promise<{ searchResults: { documents: { id: string; name: string }[] } }>;
+};
diff --git a/apps/papra-server/src/modules/documents/document-search/document-search.usecase.ts b/apps/papra-server/src/modules/documents/document-search/document-search.usecase.ts
new file mode 100644
index 00000000..e69de29b
diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.ts
index 1d3df866..a18a1751 100644
--- a/apps/papra-server/src/modules/documents/documents.routes.ts
+++ b/apps/papra-server/src/modules/documents/documents.routes.ts
@@ -301,7 +301,7 @@ function setupGetDocumentFileRoute({ app, db, documentsStorageService }: RouteDe
);
}
-function setupSearchDocumentsRoute({ app, db }: RouteDefinitionContext) {
+function setupSearchDocumentsRoute({ app, db, documentSearchServices }: RouteDefinitionContext) {
app.get(
'/api/organizations/:organizationId/documents/search',
requireAuthentication({ apiKeyPermissions: ['documents:read'] }),
@@ -321,15 +321,14 @@ function setupSearchDocumentsRoute({ app, db }: RouteDefinitionContext) {
const { organizationId } = context.req.valid('param');
const { searchQuery, pageIndex, pageSize } = context.req.valid('query');
- const documentsRepository = createDocumentsRepository({ db });
const organizationsRepository = createOrganizationsRepository({ db });
await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
- const { documents } = await documentsRepository.searchOrganizationDocuments({ organizationId, searchQuery, pageIndex, pageSize });
+ const { searchResults } = await documentSearchServices.searchDocuments({ organizationId, searchQuery, pageIndex, pageSize });
return context.json({
- documents: formatDocumentsForApi({ documents }),
+ searchResults,
});
},
);