The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Fail a record export when a page fetch fails instead of truncating it (#26125)
Charles Bochet290022e0a3c7
diff --git a/packages/twenty-front/src/modules/blocknote-editor/hooks/useAttachmentSync.ts b/packages/twenty-front/src/modules/blocknote-editor/hooks/useAttachmentSync.tsindex 7ee03924dc8..8aaaaabe281 100644--- a/packages/twenty-front/src/modules/blocknote-editor/hooks/useAttachmentSync.ts+++ b/packages/twenty-front/src/modules/blocknote-editor/hooks/useAttachmentSync.ts@@ -8,6 +8,9 @@ import { useDeleteManyRecords } from '@/object-record/hooks/useDeleteManyRecordsimport { useLazyFetchAllRecords } from '@/object-record/hooks/useLazyFetchAllRecords';import { useRestoreManyRecords } from '@/object-record/hooks/useRestoreManyRecords';import { useUpdateOneRecord } from '@/object-record/hooks/useUpdateOneRecord';+import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';+import { isDefined } from 'twenty-shared/utils';+import { useToast } from 'twenty-ui/primitives/feedback';export const useAttachmentSync = (attachments: Attachment[]) => {const { deleteManyRecords: deleteAttachments } = useDeleteManyRecords({@@ -29,6 +32,7 @@ export const useAttachmentSync = (attachments: Attachment[]) => {});const { updateOneRecord } = useUpdateOneRecord();+ const { enqueueToast } = useToast();const syncAttachments = async (newBody: string,@@ -56,17 +60,24 @@ export const useAttachmentSync = (attachments: Attachment[]) => {);if (attachmentPathsToRestore.length > 0) {- const softDeletedAttachments =- (await findSoftDeletedAttachments()) as Attachment[];+ const softDeletedAttachments = (await findSoftDeletedAttachments().catch(+ (error) => {+ enqueueToast(getToastOptionsFromError({ error }));- const attachmentIdsToRestore = filterAttachmentsToRestore({- attachmentPathsToRestore,- softDeletedAttachments: softDeletedAttachments ?? [],- });+ return null;+ },+ )) as Attachment[] | null;- await restoreAttachments({- idsToRestore: attachmentIdsToRestore,- });+ if (isDefined(softDeletedAttachments)) {+ const attachmentIdsToRestore = filterAttachmentsToRestore({+ attachmentPathsToRestore,+ softDeletedAttachments,+ });++ await restoreAttachments({+ idsToRestore: attachmentIdsToRestore,+ });+ }}const attachmentsToUpdate = getActivityAttachmentIdsAndNameToUpdate(diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/components/HeadlessConfirmationModalEngineCommandEffect.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/components/HeadlessConfirmationModalEngineCommandEffect.tsxindex c18fe5177ec..4f4f172f355 100644--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/components/HeadlessConfirmationModalEngineCommandEffect.tsx+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/components/HeadlessConfirmationModalEngineCommandEffect.tsx@@ -7,7 +7,9 @@ import { type CommandMenuItemConfirmationModalLinkButton } from '@/command-menu-import { type CommandMenuConfirmationModalResultBrowserEventDetail } from 'twenty-shared/types';import { useUnmountCommand } from '@/command-menu-item/engine-command/hooks/useUnmountEngineCommand';import { CommandComponentInstanceContext } from '@/command-menu-item/engine-command/states/contexts/CommandComponentInstanceContext';+import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';+import { useToast } from 'twenty-ui/primitives/feedback';import { type ButtonColor } from 'twenty-ui/primitives/input';export type HeadlessConfirmationModalEngineCommandEffectProps = {@@ -35,6 +37,7 @@ export const HeadlessConfirmationModalEngineCommandEffect = ({);const unmountCommand = useUnmountCommand();const { openConfirmationModal } = useCommandMenuConfirmationModal();+ const { enqueueToast } = useToast();useEffect(() => {if (isInitializedRef.current) {@@ -77,11 +80,15 @@ export const HeadlessConfirmationModalEngineCommandEffect = ({return;}- if (customEvent.detail.confirmationResult === 'confirm') {- await execute();+ try {+ if (customEvent.detail.confirmationResult === 'confirm') {+ await execute();+ }+ } catch (error) {+ enqueueToast(getToastOptionsFromError({ error }));+ } finally {+ unmountCommand(commandMenuItemId);}-- unmountCommand(commandMenuItemId);};window.addEventListener(@@ -95,7 +102,7 @@ export const HeadlessConfirmationModalEngineCommandEffect = ({handleConfirmationResult,);};- }, [execute, commandMenuItemId, unmountCommand]);+ }, [execute, commandMenuItemId, unmountCommand, enqueueToast]);return null;};diff --git a/packages/twenty-front/src/modules/object-record/hooks/__tests__/useLazyFetchAllRecords.test.tsx b/packages/twenty-front/src/modules/object-record/hooks/__tests__/useLazyFetchAllRecords.test.tsxindex d35eaa407e9..77ae155e88b 100644--- a/packages/twenty-front/src/modules/object-record/hooks/__tests__/useLazyFetchAllRecords.test.tsx+++ b/packages/twenty-front/src/modules/object-record/hooks/__tests__/useLazyFetchAllRecords.test.tsx@@ -121,15 +121,58 @@ const mock: MockedResponse = {})),};-const Wrapper = getJestMetadataAndApolloMocksAndCommandMenuWrapper({- apolloMocks: [mock],- componentInstanceId: 'recordIndexId',- contextStoreTargetedRecordsRule: {- mode: 'selection',- selectedRecordIds: [],+const firstPageMock: MockedResponse = {+ request: mock.request,+ result: jest.fn(() => ({+ data: {+ people: {+ pageInfo: {+ hasNextPage: true,+ hasPreviousPage: false,+ startCursor: '1',+ endCursor: '2',+ },+ totalCount: 4,+ edges: [+ {+ node: mockPerson,+ cursor: '1',+ },+ {+ node: mockPerson,+ cursor: '2',+ },+ ],+ },+ },+ })),+};++const failingSecondPageMock: MockedResponse = {+ request: {+ query: mock.request.query,+ variables: { limit: 30, lastCursor: '2' },},- contextStoreCurrentObjectMetadataNameSingular: 'person',-});+ error: new Error('Internal server error'),+};++const failingFirstPageMock: MockedResponse = {+ request: mock.request,+ error: new Error('Internal server error'),+};++const getWrapper = (apolloMocks: MockedResponse[]) =>+ getJestMetadataAndApolloMocksAndCommandMenuWrapper({+ apolloMocks,+ componentInstanceId: 'recordIndexId',+ contextStoreTargetedRecordsRule: {+ mode: 'selection',+ selectedRecordIds: [],+ },+ contextStoreCurrentObjectMetadataNameSingular: 'person',+ });++const Wrapper = getWrapper([mock]);describe('useLazyFetchAllRecords', () => {const objectNameSingular = 'person';@@ -171,4 +214,47 @@ describe('useLazyFetchAllRecords', () => {expect(finalResult).toEqual([mockPerson, mockPerson]);});++ it('fails instead of returning a truncated list when a later page fails', async () => {+ const { result } = renderHook(+ () =>+ useLazyFetchAllRecords({+ objectNameSingular,+ limit: 30,+ }),+ {+ wrapper: getWrapper([firstPageMock, failingSecondPageMock]),+ },+ );++ await act(async () => {+ await expect(result.current.fetchAllRecords()).rejects.toThrow(+ 'Internal server error',+ );+ });++ expect(result.current.isDownloading).toBe(false);+ expect(result.current.progress).toEqual({ displayType: 'number' });+ });++ it('fails when the first page fails', async () => {+ const { result } = renderHook(+ () =>+ useLazyFetchAllRecords({+ objectNameSingular,+ limit: 30,+ }),+ {+ wrapper: getWrapper([failingFirstPageMock]),+ },+ );++ await act(async () => {+ await expect(result.current.fetchAllRecords()).rejects.toThrow(+ 'Internal server error',+ );+ });++ expect(result.current.isDownloading).toBe(false);+ });});diff --git a/packages/twenty-front/src/modules/object-record/hooks/useLazyFetchAllRecords.ts b/packages/twenty-front/src/modules/object-record/hooks/useLazyFetchAllRecords.tsindex 01d84c47ffd..030032ff755 100644--- a/packages/twenty-front/src/modules/object-record/hooks/useLazyFetchAllRecords.ts+++ b/packages/twenty-front/src/modules/object-record/hooks/useLazyFetchAllRecords.ts@@ -35,6 +35,7 @@ export const useLazyFetchAllRecords = <T>({orderBy,limit,recordGqlFields,+ shouldToastOnError: false,});const { objectMetadataItem } = useObjectMetadataItem({@@ -47,73 +48,83 @@ export const useLazyFetchAllRecords = <T>({}setIsDownloading(true);- const findManyRecordsDataResult = await findManyRecordsLazy();+ try {+ const findManyRecordsDataResult = await findManyRecordsLazy();- const firstQueryResult =- findManyRecordsDataResult?.data?.[objectMetadataItem.namePlural];+ if (isDefined(findManyRecordsDataResult.error)) {+ throw findManyRecordsDataResult.error;+ }- const totalCount = firstQueryResult?.totalCount ?? 0;+ const firstQueryResult =+ findManyRecordsDataResult.data?.[objectMetadataItem.namePlural];- const recordsCount = firstQueryResult?.edges.length ?? 0;+ const totalCount = firstQueryResult?.totalCount ?? 0;- const records = firstQueryResult?.edges?.map((edge) => edge.node) ?? [];+ const recordsCount = firstQueryResult?.edges.length ?? 0;- setProgress({- processedRecordCount: recordsCount,- totalRecordCount: totalCount,- displayType: totalCount ? 'percentage' : 'number',- });+ const records = firstQueryResult?.edges?.map((edge) => edge.node) ?? [];- const remainingCount = totalCount - recordsCount;+ setProgress({+ processedRecordCount: recordsCount,+ totalRecordCount: totalCount,+ displayType: totalCount ? 'percentage' : 'number',+ });- const remainingPages = Math.ceil(remainingCount / limit);+ const remainingCount = totalCount - recordsCount;- let lastCursor = firstQueryResult?.pageInfo.endCursor ?? null;+ const remainingPages = Math.ceil(remainingCount / limit);- for (- let pageIndex = 0;- pageIndex < Math.min(maximumRequests, remainingPages);- pageIndex++- ) {- if (lastCursor === null) {- break;- }+ let lastCursor = firstQueryResult?.pageInfo.endCursor ?? null;- if (!isDefined(fetchMoreRecordsLazy)) {- break;- }+ for (+ let pageIndex = 0;+ pageIndex < Math.min(maximumRequests, remainingPages);+ pageIndex+++ ) {+ if (lastCursor === null) {+ break;+ }- if (delayMs > 0) {- await sleep(delayMs);- }+ if (!isDefined(fetchMoreRecordsLazy)) {+ break;+ }- const rawResult = await fetchMoreRecordsLazy(limit);+ if (delayMs > 0) {+ await sleep(delayMs);+ }- const fetchMoreResult = rawResult?.data;+ const rawResult = await fetchMoreRecordsLazy(limit);- for (const edge of fetchMoreResult?.edges ?? []) {- records.push(edge.node);- }+ if (isDefined(rawResult) && 'error' in rawResult) {+ throw rawResult.error;+ }- setProgress({- processedRecordCount: records.length,- totalRecordCount: totalCount,- displayType: totalCount ? 'percentage' : 'number',- });+ const fetchMoreResult = rawResult?.data;- if (fetchMoreResult?.pageInfo.hasNextPage === false) {- break;- }+ for (const edge of fetchMoreResult?.edges ?? []) {+ records.push(edge.node);+ }- lastCursor = fetchMoreResult?.pageInfo.endCursor ?? null;- }+ setProgress({+ processedRecordCount: records.length,+ totalRecordCount: totalCount,+ displayType: totalCount ? 'percentage' : 'number',+ });- setIsDownloading(false);- setProgress({- displayType: 'number',- });+ if (fetchMoreResult?.pageInfo.hasNextPage === false) {+ break;+ }- return records;+ lastCursor = fetchMoreResult?.pageInfo.endCursor ?? null;+ }++ return records;+ } finally {+ setIsDownloading(false);+ setProgress({+ displayType: 'number',+ });+ }}, [delayMs,fetchMoreRecordsLazy,diff --git a/packages/twenty-front/src/modules/object-record/hooks/useLazyFetchMoreRecordsWithPagination.ts b/packages/twenty-front/src/modules/object-record/hooks/useLazyFetchMoreRecordsWithPagination.tsindex b1850643ad0..d181ef7bc23 100644--- a/packages/twenty-front/src/modules/object-record/hooks/useLazyFetchMoreRecordsWithPagination.ts+++ b/packages/twenty-front/src/modules/object-record/hooks/useLazyFetchMoreRecordsWithPagination.ts@@ -63,6 +63,7 @@ type UseFindManyRecordsStateParams<>,): Promise<ApolloClient.QueryResult<TFetchData>>;objectMetadataItem: EnrichedObjectMetadataItem;+ shouldToastOnError?: boolean;};export const useLazyFetchMoreRecordsWithPagination = <@@ -75,6 +76,7 @@ export const useLazyFetchMoreRecordsWithPagination = <error,fetchMore,objectMetadataItem,+ shouldToastOnError = true,}: UseFindManyRecordsStateParams<T>) => {const store = useStore();const queryIdentifier = getQueryIdentifier({@@ -176,7 +178,9 @@ export const useLazyFetchMoreRecordsWithPagination = <}) as T[],};} catch (error) {- handleFindManyRecordsError(error as ErrorLike);+ if (shouldToastOnError) {+ handleFindManyRecordsError(error as ErrorLike);+ }return { error: error as ErrorLike };}}@@ -189,6 +193,7 @@ export const useLazyFetchMoreRecordsWithPagination = <filter,orderBy,handleFindManyRecordsError,+ shouldToastOnError,store,],);diff --git a/packages/twenty-front/src/modules/object-record/hooks/useLazyFindManyRecords.ts b/packages/twenty-front/src/modules/object-record/hooks/useLazyFindManyRecords.tsindex 02e7ccf4878..2e2cf481695 100644--- a/packages/twenty-front/src/modules/object-record/hooks/useLazyFindManyRecords.ts+++ b/packages/twenty-front/src/modules/object-record/hooks/useLazyFindManyRecords.ts@@ -21,7 +21,9 @@ import { useStore } from 'jotai';type UseLazyFindManyRecordsParams<T> = Omit<UseFindManyRecordsParams<T>,'skip' | 'onCompleted' | 'onError'->;+> & {+ shouldToastOnError?: boolean;+};export const useLazyFindManyRecords = <T extends ObjectRecord = ObjectRecord>({objectNameSingular,@@ -30,6 +32,7 @@ export const useLazyFindManyRecords = <T extends ObjectRecord = ObjectRecord>({limit = QUERY_DEFAULT_LIMIT_RECORDS,recordGqlFields,fetchPolicy = 'cache-first',+ shouldToastOnError = true,}: UseLazyFindManyRecordsParams<T>) => {const store = useStore();const { objectMetadataItem } = useObjectMetadataItem({@@ -84,6 +87,7 @@ export const useLazyFindManyRecords = <T extends ObjectRecord = ObjectRecord>({data: data as RecordGqlOperationFindManyResult | undefined,error,objectMetadataItem,+ shouldToastOnError,});const findManyRecordsLazy = useCallback(async () => {@@ -108,7 +112,7 @@ export const useLazyFindManyRecords = <T extends ObjectRecord = ObjectRecord>({variables: defaultVariables,}).retain();- if (isDefined(result?.error)) {+ if (isDefined(result?.error) && shouldToastOnError) {handleFindManyRecordsError(result.error);}@@ -151,6 +155,7 @@ export const useLazyFindManyRecords = <T extends ObjectRecord = ObjectRecord>({objectMetadataItem.namePlural,queryIdentifier,handleFindManyRecordsError,+ shouldToastOnError,store,]);