Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

refactor(server): custom pick utility to replace lodash-es (#1007)

Corentin Thomassetdb988e990d44
diff --git a/apps/papra-server/src/modules/api-keys/api-keys.repository.ts b/apps/papra-server/src/modules/api-keys/api-keys.repository.ts
index 26132d17..33568313 100644
--- a/apps/papra-server/src/modules/api-keys/api-keys.repository.ts
+++ b/apps/papra-server/src/modules/api-keys/api-keys.repository.ts
@@ -3,10 +3,11 @@ import type { Logger } from '../shared/logger/logger';
import type { ApiKeyPermissions } from './api-keys.types';
import { injectArguments } from '@corentinth/chisels';
import { and, eq, getTableColumns, gt, inArray, isNull, or } from 'drizzle-orm';
-import { omit, pick } from 'lodash-es';
+import { omit } from 'lodash-es';
import { organizationMembersTable, organizationsTable } from '../organizations/organizations.table';
import { createError } from '../shared/errors/errors';
import { createLogger } from '../shared/logger/logger';
+import { pick } from '../shared/objects';
import { apiKeyOrganizationsTable, apiKeysTable } from './api-keys.tables';
export type ApiKeysRepository = ReturnType<typeof createApiKeysRepository>;
diff --git a/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.repository.test.ts b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.repository.test.ts
index 4547a54b..4e8892ad 100644
--- a/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.repository.test.ts
+++ b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.repository.test.ts
@@ -1,19 +1,21 @@
import type { Database } from '../../app/database/database.types';
import { getTableColumns } from 'drizzle-orm';
-import { pick } from 'lodash-es';
import { describe, expect, test } from 'vitest';
import { createInMemoryDatabase } from '../../app/database/database.test-utils';
+import { pick } from '../../shared/objects';
import { CUSTOM_PROPERTY_TYPES } from '../custom-properties.constants';
import { createCustomPropertySelectOptionUnknownIdError } from './custom-properties-options.errors';
import { createCustomPropertiesOptionsRepository } from './custom-properties-options.repository';
import { customPropertySelectOptionsTable } from './custom-properties-options.table';
async function getOptions({ db, withId = true }: { db: Database; withId?: boolean }) {
+ const props = ['propertyDefinitionId', 'name', 'key', 'displayOrder'] as const;
+
return db
.select({
...pick(
getTableColumns(customPropertySelectOptionsTable),
- [...(withId ? ['id'] : []), 'propertyDefinitionId', 'name', 'key', 'displayOrder'],
+ withId ? ['id', ...props] : props,
),
})
.from(customPropertySelectOptionsTable);
diff --git a/apps/papra-server/src/modules/intake-emails/e2e/ingest-intake-emails.e2e.test.ts b/apps/papra-server/src/modules/intake-emails/e2e/ingest-intake-emails.e2e.test.ts
index a2344128..790c319c 100644
--- a/apps/papra-server/src/modules/intake-emails/e2e/ingest-intake-emails.e2e.test.ts
+++ b/apps/papra-server/src/modules/intake-emails/e2e/ingest-intake-emails.e2e.test.ts
@@ -1,6 +1,5 @@
import type { Document } from '../../documents/documents.types';
import { serializeEmailForWebhook, signBody } from '@owlrelay/webhook';
-import { pick } from 'lodash-es';
import { describe, expect, test } from 'vitest';
import { createInMemoryDatabase } from '../../app/database/database.test-utils';
import { createServer } from '../../app/server';
@@ -8,6 +7,7 @@ import { createTestServerDependencies } from '../../app/server.test-utils';
import { overrideConfig } from '../../config/config.test-utils';
import { ORGANIZATION_ROLES } from '../../organizations/organizations.constants';
import { MIME_TYPES } from '../../shared/mime-types/mime-types.constants';
+import { pick } from '../../shared/objects';
describe('intake-emails e2e', () => {
describe('ingest an intake email', () => {
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts
index 5e65816e..43d6a28c 100644
--- a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts
@@ -1,7 +1,6 @@
import type { PlansRepository } from '../plans/plans.repository';
import { createInMemoryLoggerTransport, createLogger } from '@crowlog/logger';
import { asc } from 'drizzle-orm';
-import { pick } from 'lodash-es';
import { describe, expect, test } from 'vitest';
import { createInMemoryDatabase } from '../app/database/database.test-utils';
import { createTestEventServices } from '../app/events/events.test-utils';
@@ -10,6 +9,7 @@ import { documentsTable } from '../documents/documents.table';
import { createDocumentCreationUsecase } from '../documents/documents.usecases';
import { createInMemoryDocumentStorageServices } from '../documents/storage/documents.storage.services.test-utils';
import { PLUS_PLAN_ID } from '../plans/plans.constants';
+import { pick } from '../shared/objects';
import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';
import { createInMemoryTaskServices } from '../tasks/tasks.test-utils';
import { createIntakeEmailLimitReachedError } from './intake-emails.errors';
diff --git a/apps/papra-server/src/modules/shared/fs/fs.services.ts b/apps/papra-server/src/modules/shared/fs/fs.services.ts
index 55339fe1..e4ef55fe 100644
--- a/apps/papra-server/src/modules/shared/fs/fs.services.ts
+++ b/apps/papra-server/src/modules/shared/fs/fs.services.ts
@@ -3,7 +3,7 @@ import { Buffer } from 'node:buffer';
import fsSyncNative from 'node:fs';
import fsPromisesNative from 'node:fs/promises';
import { injectArguments, safely } from '@corentinth/chisels';
-import { pick } from 'lodash-es';
+import { pick } from '../objects';
import { isCrossDeviceError } from './fs.models';
// what we use from the native fs module
@@ -20,7 +20,7 @@ export type FsNative = {
};
const fsNative = {
- ...pick(fsPromisesNative, 'mkdir', 'unlink', 'rename', 'readFile', 'access', 'constants', 'stat', 'copyFile'),
+ ...pick(fsPromisesNative, ['mkdir', 'unlink', 'rename', 'readFile', 'access', 'constants', 'stat', 'copyFile']),
createReadStream: fsSyncNative.createReadStream.bind(fsSyncNative) as (filePath: string) => Readable,
} as FsNative;
diff --git a/apps/papra-server/src/modules/shared/objects.test.ts b/apps/papra-server/src/modules/shared/objects.test.ts
new file mode 100644
index 00000000..69be6ba6
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/objects.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, test } from 'vitest';
+import { pick } from './objects';
+
+describe('objects', () => {
+ describe('pick', () => {
+ test('given an object and a list of keys, return a new object with only the specified keys', () => {
+ expect(pick({ a: 1, b: 2 }, ['a'])).toEqual({ a: 1 });
+ });
+
+ test('when a key is not present in the object, it is ignored', () => {
+ expect(pick({ a: 1, b: 2 }, ['a', 'c'] as ('a' | 'b')[])).toEqual({ a: 1 });
+ });
+
+ test('when a key is duplicated, it obviously only appears once in the result', () => {
+ expect(pick({ a: 1, b: 2 }, ['a', 'a'])).toEqual({ a: 1 });
+ });
+
+ test('when the object is empty, the result is always an empty object', () => {
+ expect(pick({}, [])).toEqual({});
+ expect(pick({}, ['a', 'b'] as unknown as never[])).toEqual({});
+ });
+
+ test('when the list of keys is empty, the result is always an empty object', () => {
+ expect(pick({ a: 1, b: 2 }, [])).toEqual({});
+ });
+
+ test('nested keys are not supported', () => {
+ expect(pick({ a: { b: 1 } }, ['a'])).toEqual({ a: { b: 1 } });
+ expect(pick({ a: { b: 1 } }, ['a.b'] as unknown as never[])).toEqual({});
+ });
+
+ test('resulting object is a new object, not a reference to the original one', () => {
+ const obj = { a: 1, b: 2 };
+ const result = pick(obj, ['a']);
+ expect(result).toEqual({ a: 1 });
+ expect(result).not.toBe(obj);
+ });
+
+ test('properties references are preserved', () => {
+ const user = { name: 'Alice' };
+
+ const obj = { user, b: 2 };
+ const result = pick(obj, ['user']);
+
+ expect(result).toEqual({ user: { name: 'Alice' } });
+ expect(result.user).toBe(user);
+ });
+
+ test('when the object has properties in its prototype chain, they are ignored', () => {
+ // eslint-disable-next-line ts/no-unsafe-assignment
+ const obj = Object.create({ a: 1 });
+ // eslint-disable-next-line ts/no-unsafe-member-access
+ obj.b = 2;
+
+ expect(pick(obj, ['a', 'b'] as unknown as never[])).toEqual({ b: 2 });
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/shared/objects.ts b/apps/papra-server/src/modules/shared/objects.ts
new file mode 100644
index 00000000..74f48b81
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/objects.ts
@@ -0,0 +1,11 @@
+export function pick<T extends object, K extends keyof T>(obj: T, keys: K[] | readonly K[]): Pick<T, K> {
+ const result = {} as Pick<T, K>;
+
+ for (const key of keys) {
+ if (Object.hasOwn(obj, key)) {
+ result[key] = obj[key];
+ }
+ }
+
+ return result;
+}
diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts
index 9ca0813f..dde27b35 100644
--- a/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts
+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts
@@ -1,5 +1,4 @@
import type { RouteDefinitionContext } from '../app/server.types';
-import { pick } from 'lodash-es';
import { z } from 'zod';
import { requireAuthentication } from '../app/auth/auth.middleware';
import { getUser } from '../app/auth/auth.models';
@@ -15,6 +14,7 @@ import { createPlansRepository } from '../plans/plans.repository';
import { getOrganizationPlan } from '../plans/plans.usecases';
import { getHeader } from '../shared/headers/headers.models';
import { createLogger } from '../shared/logger/logger';
+import { pick } from '../shared/objects';
import { nullifyPositiveInfinity } from '../shared/utils';
import { validateJsonBody, validateParams } from '../shared/validation/validation';
import { createInvalidWebhookPayloadError, createOrganizationAlreadyHasSubscriptionError } from './subscriptions.errors';
diff --git a/apps/papra-server/src/modules/users/users.routes.ts b/apps/papra-server/src/modules/users/users.routes.ts
index b96b84d0..988ecf19 100644
--- a/apps/papra-server/src/modules/users/users.routes.ts
+++ b/apps/papra-server/src/modules/users/users.routes.ts
@@ -1,10 +1,10 @@
import type { RouteDefinitionContext } from '../app/server.types';
-import { pick } from 'lodash-es';
import { z } from 'zod';
import { requireAuthentication } from '../app/auth/auth.middleware';
import { getUser } from '../app/auth/auth.models';
import { getPermissionsForRoles } from '../roles/roles.methods';
import { createRolesRepository } from '../roles/roles.repository';
+import { pick } from '../shared/objects';
import { validateJsonBody } from '../shared/validation/validation';
import { createUsersRepository } from './users.repository';
@@ -35,7 +35,6 @@ function setupGetCurrentUserRoute({ app, db }: RouteDefinitionContext) {
return context.json({
user: {
- permissions,
...pick(
user,
[
@@ -44,10 +43,11 @@ function setupGetCurrentUserRoute({ app, db }: RouteDefinitionContext) {
'name',
'createdAt',
'updatedAt',
- 'planId',
'twoFactorEnabled',
],
),
+
+ permissions,
},
});
},