The minimalistic document archiving platform.
refactor(server): replaced remaning lodash-es get with type-safe property access (#1006)
Corentin Thomassetef89ea675170
diff --git a/apps/papra-server/src/modules/app/auth/auth.routes.ts b/apps/papra-server/src/modules/app/auth/auth.routes.tsindex 15e9fd3d..49a321c3 100644--- a/apps/papra-server/src/modules/app/auth/auth.routes.ts+++ b/apps/papra-server/src/modules/app/auth/auth.routes.ts@@ -1,8 +1,20 @@import type { Context, RouteDefinitionContext } from '../server.types';import type { Session } from './auth.types';-import { get } from 'lodash-es';import { addLogContext } from '../../shared/logger/logger';-import { isDefined, isNil, isString } from '../../shared/utils';+import { isDefined, isNil } from '../../shared/utils';++function getOverrideUserId(context: Context): string | undefined {+ if (+ !isNil(context.env)+ && typeof context.env === 'object'+ && 'loggedInUserId' in context.env+ && typeof context.env.loggedInUserId === 'string'+ ) {+ return context.env.loggedInUserId;+ }++ return undefined;+}export function registerAuthRoutes({ app, auth, config }: RouteDefinitionContext) {app.on(@@ -38,9 +50,9 @@ export function registerAuthRoutes({ app, auth, config }: RouteDefinitionContextif (config.env === 'test') {app.use('*', async (context: Context, next) => {- const overrideUserId: unknown = get(context.env, 'loggedInUserId');+ const overrideUserId = getOverrideUserId(context);- if (isDefined(overrideUserId) && isString(overrideUserId)) {+ if (isDefined(overrideUserId)) {context.set('userId', overrideUserId);context.set('session', {} as Session);context.set('authType', 'session');diff --git a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.models.test.ts b/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.models.test.tsnew file mode 100644index 00000000..1eecc66a--- /dev/null+++ b/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.models.test.ts@@ -0,0 +1,43 @@+import { readFile } from 'node:fs/promises';+import { safely } from '@corentinth/chisels';++import { describe, expect, test } from 'vitest';+import { isFileNotFoundError } from './fs.storage-driver.models';++const makeNonexistentFilePath = () => `unexisting-file-${Math.random().toString(36).substring(2)}`;++describe('fs storage driver models', () => {+ describe('isFileNotFoundError', () => {+ test('file not found errors have a code property equal to ENOENT', () => {+ expect(isFileNotFoundError({ error: Object.assign(new Error('File not found'), { code: 'ENOENT' }) })).to.eql(true);+ expect(isFileNotFoundError({ error: { code: 'ENOENT' } })).to.eql(true);++ expect(isFileNotFoundError({ error: Object.assign(new Error('Some other error'), { code: 'SOME_OTHER_CODE' }) })).to.eql(false);+ expect(isFileNotFoundError({ error: new Error('File not found without code') })).to.eql(false);+ expect(isFileNotFoundError({ error: null })).to.eql(false);+ expect(isFileNotFoundError({ error: undefined })).to.eql(false);+ expect(isFileNotFoundError({ error: 'Some string error' })).to.eql(false);+ expect(isFileNotFoundError({ error: 123 })).to.eql(false);+ });++ test('real file not found error from fs.promises catched using safely is detected as file not found error', async () => {+ const [fileContent, error] = await safely(readFile(makeNonexistentFilePath(), 'utf-8'));++ expect(fileContent).to.eql(null);+ expect(isFileNotFoundError({ error })).to.eql(true);+ });++ test('real file not found error from fs.promises catched using try/catch is detected as file not found error', async () => {+ let error: unknown;++ try {+ await readFile(makeNonexistentFilePath(), 'utf-8');+ expect.fail('Expected readFile to throw an error');+ } catch (err) {+ error = err;+ }++ expect(isFileNotFoundError({ error })).to.eql(true);+ });+ });+});diff --git a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.models.ts b/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.models.tsnew file mode 100644index 00000000..4f825e20--- /dev/null+++ b/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.models.ts@@ -0,0 +1,8 @@+import { isNil } from '../../../../shared/utils';++export function isFileNotFoundError({ error }: { error?: unknown }): boolean {+ return !isNil(error)+ && typeof error === 'object'+ && 'code' in error+ && error.code === 'ENOENT';+}diff --git a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.ts b/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.tsindex 7761a89c..8649469f 100644--- a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.ts+++ b/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.ts@@ -1,10 +1,11 @@import fs from 'node:fs';import { dirname, join } from 'node:path';-import { get } from 'lodash-es';+import { safely } from '@corentinth/chisels';import { isFileAlreadyExistsError } from '../../../../shared/fs/fs.models';import { checkFileExists, deleteFile, ensureDirectoryExists } from '../../../../shared/fs/fs.services';import { createFileAlreadyExistsInStorageError, createFileNotFoundError } from '../../document-storage.errors';import { defineStorageDriver } from '../drivers.models';+import { isFileNotFoundError } from './fs.storage-driver.models';export const FS_STORAGE_DRIVER_NAME = 'filesystem' as const;@@ -63,13 +64,13 @@ export const fsStorageDriverFactory = defineStorageDriver(({ documentStorageConfdeleteFile: async ({ storageKey }) => {const { storagePath } = getStoragePath({ storageKey });- try {- await deleteFile({ filePath: storagePath });- } catch (error) {- if (get(error, 'code') === 'ENOENT') {- throw createFileNotFoundError();- }+ const [, error] = await safely(deleteFile({ filePath: storagePath }));+ if (error && isFileNotFoundError({ error })) {+ throw createFileNotFoundError();+ }++ if (error) {throw error;}},diff --git a/apps/papra-server/src/modules/shared/db/constraints.models.ts b/apps/papra-server/src/modules/shared/db/constraints.models.tsindex e9a75530..7c79b433 100644--- a/apps/papra-server/src/modules/shared/db/constraints.models.ts+++ b/apps/papra-server/src/modules/shared/db/constraints.models.ts@@ -1,8 +1,12 @@-import { get } from 'lodash-es';+import { isNil } from '../utils';export function isUniqueConstraintError({ error }: { error: unknown }): boolean {- const message: unknown = get(error, 'message');- const code: unknown = get(error, 'code');+ if (isNil(error) || typeof error !== 'object') {+ return false;+ }++ const message: unknown = 'message' in error ? error.message : undefined;+ const code: unknown = 'code' in error ? error.code : undefined;if (code === 'SQLITE_CONSTRAINT_UNIQUE') {return true;diff --git a/apps/papra-server/src/modules/shared/errors/errors.ts b/apps/papra-server/src/modules/shared/errors/errors.tsindex 4a06dc84..4b626485 100644--- a/apps/papra-server/src/modules/shared/errors/errors.ts+++ b/apps/papra-server/src/modules/shared/errors/errors.ts@@ -1,5 +1,5 @@import type { ContentfulStatusCode } from 'hono/utils/http-status';-import { get, isError, toString } from 'lodash-es';+import { isError } from 'lodash-es';export { createError, createErrorFactory, formatPublicErrorPayload, isCustomError, isErrorWithCode };@@ -22,7 +22,7 @@ class CustomError extends Error {super(message);this.code = code;- this.cause = isError(cause) ? cause : new Error(toString(cause));+ this.cause = isError(cause) ? cause : new Error(String(cause));this.statusCode = statusCode;this.isInternal = isInternal;}@@ -43,7 +43,7 @@ function createErrorFactory(baseOption: ErrorOptions) {}function isCustomError(error: unknown): error is CustomError {- return get(error, 'isCustomError') === true && isError(error);+ return isError(error) && 'isCustomError' in error && error.isCustomError === true;}function isErrorWithCode({ error, code }: { error: unknown; code: string }) {diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.routes.tsindex c64f4cfe..9ca0813f 100644--- a/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts@@ -1,5 +1,5 @@import type { RouteDefinitionContext } from '../app/server.types';-import { get, pick } from 'lodash-es';+import { pick } from 'lodash-es';import { z } from 'zod';import { requireAuthentication } from '../app/auth/auth.middleware';import { getUser } from '../app/auth/auth.models';@@ -49,7 +49,7 @@ function setupStripeWebhookRoute({ app, config, db, subscriptionsServices }: Roulogger.info({event: pick(event, ['id', 'type']),- customerId: get(event, 'data.object.customer'),+ customerId: 'customer' in event.data.object ? event.data.object.customer : undefined,},'Stripe webhook received',);diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.usecases.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.usecases.tsindex 4051b304..8d85f0e2 100644--- a/apps/papra-server/src/modules/subscriptions/subscriptions.usecases.ts+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.usecases.ts@@ -3,7 +3,6 @@ import type { PlansRepository } from '../plans/plans.repository';import type { Logger } from '../shared/logger/logger';import type { SubscriptionsRepository } from './subscriptions.repository';import type { SubscriptionsServices } from './subscriptions.services';-import { get } from 'lodash-es';import { createOrganizationNotFoundError } from '../organizations/organizations.errors';import { createLogger } from '../shared/logger/logger';import { isNil } from '../shared/utils';@@ -24,7 +23,7 @@ export async function handleStripeWebhookEvent({}) {if (event.type === 'customer.subscription.created' || event.type === 'customer.subscription.updated') {const subscriptionId = event.data.object.id;- const organizationId = get(event, 'data.object.metadata.organizationId') as string | undefined;+ const organizationId = event.data.object.metadata.organizationId;if (isNil(organizationId)) {throw createOrganizationNotFoundError();diff --git a/apps/papra-server/src/modules/tagging-rules/tagging-rules.models.ts b/apps/papra-server/src/modules/tagging-rules/tagging-rules.models.tsindex 56e846a0..bc100e97 100644--- a/apps/papra-server/src/modules/tagging-rules/tagging-rules.models.ts+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.models.ts@@ -1,8 +1,7 @@import type { Document } from '../documents/documents.types';-import { get } from 'lodash-es';export function getDocumentFieldValue({ document, field }: { document: Document; field: string }) {- const fieldValue: unknown = get(document, field);+ const fieldValue: unknown = Object.hasOwn(document, field) ? document[field as keyof Document] : undefined;return { fieldValue: String(fieldValue ?? '') };}