Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

refactor(documents): migrate route validation from zod to valibot (#1038)

Corentin Thomasset791d08c48698
diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.ts
index c1a1c367..33f7d4d2 100644
--- a/apps/papra-server/src/modules/documents/documents.routes.ts
+++ b/apps/papra-server/src/modules/documents/documents.routes.ts
@@ -1,23 +1,24 @@
import type { RouteDefinitionContext } from '../app/server.types';
import { Readable } from 'node:stream';
-import { z } from 'zod';
+import * as v from 'valibot';
import { requireAuthentication } from '../app/auth/auth.middleware';
import { getUser } from '../app/auth/auth.models';
import { createCustomPropertiesRepository } from '../custom-properties/custom-properties.repository';
-import { organizationIdSchema } from '../organizations/organization.schemas.legacy';
+import { organizationIdSchema } from '../organizations/organization.schemas';
import { createOrganizationsRepository } from '../organizations/organizations.repository';
import { ensureUserIsInOrganization } from '../organizations/organizations.usecases';
import { createPlansRepository } from '../plans/plans.repository';
import { getOrganizationPlan } from '../plans/plans.usecases';
+import { createQueryPaginationSchemaKeys } from '../shared/schemas/pagination.schemas';
import { getFileStreamFromMultipartForm } from '../shared/streams/file-upload';
-import { legacyValidateJsonBody, legacyValidateParams, legacyValidateQuery } from '../shared/validation/validation.legacy';
+import { validateJsonBody, validateParams, validateQuery } from '../shared/validation/validation';
import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';
import { createTagsRepository } from '../tags/tags.repository';
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 } from './documents.schemas.legacy';
+import { documentIdSchema, updateDocumentBodySchema } from './documents.schemas';
import { createDocumentCreationUsecase, deleteAllTrashDocuments, deleteTrashDocument, enrichAndFormatDocumentForApi, enrichAndFormatDocumentsForApi, ensureDocumentExists, getDocumentOrThrow, restoreDocument, trashDocument, updateDocument } from './documents.usecases';
export function registerDocumentsRoutes(context: RouteDefinitionContext) {
@@ -40,7 +41,7 @@ function setupCreateDocumentRoute({ app, ...deps }: RouteDefinitionContext) {
app.post(
'/api/organizations/:organizationId/documents',
requireAuthentication({ apiKeyPermissions: ['documents:create'] }),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
})),
async (context) => {
@@ -76,13 +77,12 @@ function setupGetDeletedDocumentsRoute({ app, db }: RouteDefinitionContext) {
app.get(
'/api/organizations/:organizationId/documents/deleted',
requireAuthentication({ apiKeyPermissions: ['documents:read'] }),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
})),
- legacyValidateQuery(
- z.object({
- pageIndex: z.coerce.number().min(0).int().optional().default(0),
- pageSize: z.coerce.number().min(1).max(100).int().optional().default(100),
+ validateQuery(
+ v.strictObject({
+ ...createQueryPaginationSchemaKeys({ maxPageSize: 100, defaultPageSize: 100 }),
}),
),
async (context) => {
@@ -116,7 +116,7 @@ function setupGetDocumentRoute({ app, db }: RouteDefinitionContext) {
app.get(
'/api/organizations/:organizationId/documents/:documentId',
requireAuthentication({ apiKeyPermissions: ['documents:read'] }),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
documentId: documentIdSchema,
})),
@@ -144,7 +144,7 @@ function setupDeleteDocumentRoute({ app, db, eventServices }: RouteDefinitionCon
app.delete(
'/api/organizations/:organizationId/documents/:documentId',
requireAuthentication({ apiKeyPermissions: ['documents:delete'] }),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
documentId: documentIdSchema,
})),
@@ -178,7 +178,7 @@ function setupRestoreDocumentRoute({ app, db, eventServices }: RouteDefinitionCo
app.post(
'/api/organizations/:organizationId/documents/:documentId/restore',
requireAuthentication(),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
documentId: documentIdSchema,
})),
@@ -215,7 +215,7 @@ function setupGetDocumentFileRoute({ app, db, documentsStorageService }: RouteDe
app.get(
'/api/organizations/:organizationId/documents/:documentId/file',
requireAuthentication({ apiKeyPermissions: ['documents:read'] }),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
documentId: documentIdSchema,
})),
@@ -259,14 +259,13 @@ function setupGetDocumentsRoute({ app, db, documentSearchServices }: RouteDefini
app.get(
'/api/organizations/:organizationId/documents',
requireAuthentication({ apiKeyPermissions: ['documents:read'] }),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
})),
- legacyValidateQuery(
- z.object({
- searchQuery: z.string().optional().default(''),
- pageIndex: z.coerce.number().min(0).int().optional().default(0),
- pageSize: z.coerce.number().min(1).max(100).int().optional().default(100),
+ validateQuery(
+ v.strictObject({
+ searchQuery: v.optional(v.string(), ''),
+ ...createQueryPaginationSchemaKeys({ maxPageSize: 100, defaultPageSize: 100 }),
}),
),
async (context) => {
@@ -293,7 +292,7 @@ function setupGetOrganizationDocumentsStatsRoute({ app, db }: RouteDefinitionCon
app.get(
'/api/organizations/:organizationId/documents/statistics',
requireAuthentication({ apiKeyPermissions: ['documents:read'] }),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
})),
async (context) => {
@@ -333,7 +332,7 @@ function setupDeleteTrashDocumentRoute({ app, db, documentsStorageService, event
app.delete(
'/api/organizations/:organizationId/documents/trash/:documentId',
requireAuthentication(),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
documentId: documentIdSchema,
})),
@@ -360,7 +359,7 @@ function setupDeleteAllTrashDocumentsRoute({ app, db, documentsStorageService, e
app.delete(
'/api/organizations/:organizationId/documents/trash',
requireAuthentication(),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
})),
async (context) => {
@@ -384,17 +383,11 @@ function setupUpdateDocumentRoute({ app, db, eventServices }: RouteDefinitionCon
app.patch(
'/api/organizations/:organizationId/documents/:documentId',
requireAuthentication({ apiKeyPermissions: ['documents:update'] }),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
documentId: documentIdSchema,
})),
- legacyValidateJsonBody(z.object({
- name: z.string().min(1).max(255).optional(),
- content: z.string().optional(),
- documentDate: z.coerce.date().nullable().optional(),
- }).refine(data => data.name !== undefined || data.content !== undefined || data.documentDate !== undefined, {
- message: 'At least one of \'name\', \'content\', or \'documentDate\' must be provided',
- })),
+ validateJsonBody(updateDocumentBodySchema),
async (context) => {
const { userId } = getUser({ context });
const { organizationId, documentId } = context.req.valid('param');
diff --git a/apps/papra-server/src/modules/documents/documents.schemas.test.ts b/apps/papra-server/src/modules/documents/documents.schemas.test.ts
new file mode 100644
index 00000000..7d2ae853
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/documents.schemas.test.ts
@@ -0,0 +1,53 @@
+import * as v from 'valibot';
+import { describe, expect, test } from 'vitest';
+import { updateDocumentBodySchema } from './documents.schemas';
+
+describe('documents.schemas', () => {
+ describe('updateDocumentBodySchema', () => {
+ test('parses a body with only name', () => {
+ expect(v.parse(updateDocumentBodySchema, { name: 'My Document' })).toEqual({ name: 'My Document', content: undefined, documentDate: undefined });
+ });
+
+ test('parses a body with only content', () => {
+ expect(v.parse(updateDocumentBodySchema, { content: 'Some content' })).toEqual({ name: undefined, content: 'Some content', documentDate: undefined });
+ });
+
+ test('parses a body with only documentDate as an ISO string', () => {
+ const result = v.parse(updateDocumentBodySchema, { documentDate: '2025-01-01T00:00:00.000Z' });
+ expect(result.documentDate).toBeInstanceOf(Date);
+ expect(result.documentDate?.getTime()).toBe(new Date('2025-01-01T00:00:00.000Z').getTime());
+ });
+
+ test('parses a body with documentDate as null', () => {
+ const result = v.parse(updateDocumentBodySchema, { documentDate: null });
+ expect(result.documentDate).toBeNull();
+ });
+
+ test('parses a body with all fields', () => {
+ const result = v.parse(updateDocumentBodySchema, { name: 'My Document', content: 'Some content', documentDate: '2025-06-15T12:00:00.000Z' });
+ expect(result.name).toBe('My Document');
+ expect(result.content).toBe('Some content');
+ expect(result.documentDate).toBeInstanceOf(Date);
+ });
+
+ test('fails if no field is provided', () => {
+ expect(() => v.parse(updateDocumentBodySchema, {})).toThrow();
+ });
+
+ test('fails if name is an empty string', () => {
+ expect(() => v.parse(updateDocumentBodySchema, { name: '' })).toThrow();
+ });
+
+ test('fails if name exceeds 255 characters', () => {
+ expect(() => v.parse(updateDocumentBodySchema, { name: 'a'.repeat(256) })).toThrow();
+ });
+
+ test('fails if documentDate is an invalid date string', () => {
+ expect(() => v.parse(updateDocumentBodySchema, { documentDate: 'not-a-date' })).toThrow();
+ });
+
+ test('fails if an unknown property is present', () => {
+ expect(() => v.parse(updateDocumentBodySchema, { name: 'My Document', unknown: 'field' })).toThrow();
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/documents.schemas.ts b/apps/papra-server/src/modules/documents/documents.schemas.ts
index bf9912ef..cb30c69f 100644
--- a/apps/papra-server/src/modules/documents/documents.schemas.ts
+++ b/apps/papra-server/src/modules/documents/documents.schemas.ts
@@ -1,4 +1,17 @@
+import * as v from 'valibot';
import { createRegexSchema } from '../shared/schemas/string.schemas';
import { DOCUMENT_ID_REGEX } from './documents.constants';
export const documentIdSchema = createRegexSchema(DOCUMENT_ID_REGEX);
+
+export const updateDocumentBodySchema = v.pipe(
+ v.strictObject({
+ name: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(255))),
+ content: v.optional(v.string()),
+ documentDate: v.optional(v.nullable(v.pipe(v.string(), v.toDate()))),
+ }),
+ v.check(
+ data => data.name !== undefined || data.content !== undefined || data.documentDate !== undefined,
+ 'At least one of \'name\', \'content\', or \'documentDate\' must be provided',
+ ),
+);