Files
twenty/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerAttachRelationOptimisticEffect.ts
T
Paul Rastoin 7fd89678b7 [CHORE] Avoid isDefined duplicated reference, move it to twenty-shared (#9967)
# Introduction
Avoid having multiple `isDefined` definition across our pacakges
Also avoid importing `isDefined` from `twenty-ui` which exposes a huge
barrel for a such little util function

## In a nutshell
Removed own `isDefined.ts` definition from `twenty-ui` `twenty-front`
and `twenty-server` to move it to `twenty-shared`.
Updated imports for each packages, and added explicit dependencies to
`twenty-shared` if not already in place

Related PR https://github.com/twentyhq/twenty/pull/9941
2025-02-01 12:10:10 +01:00

71 lines
2.1 KiB
TypeScript

import { ApolloCache, StoreObject } from '@apollo/client';
import { RecordGqlRefEdge } from '@/object-record/cache/types/RecordGqlRefEdge';
import { isObjectRecordConnectionWithRefs } from '@/object-record/cache/utils/isObjectRecordConnectionWithRefs';
import { capitalize, isDefined } from 'twenty-shared';
export const triggerAttachRelationOptimisticEffect = ({
cache,
sourceObjectNameSingular,
sourceRecordId,
targetObjectNameSingular,
fieldNameOnTargetRecord,
targetRecordId,
}: {
cache: ApolloCache<unknown>;
sourceObjectNameSingular: string;
sourceRecordId: string;
targetObjectNameSingular: string;
fieldNameOnTargetRecord: string;
targetRecordId: string;
}) => {
const sourceRecordTypeName = capitalize(sourceObjectNameSingular);
const targetRecordTypeName = capitalize(targetObjectNameSingular);
const targetRecordCacheId = cache.identify({
id: targetRecordId,
__typename: targetRecordTypeName,
});
cache.modify<StoreObject>({
id: targetRecordCacheId,
fields: {
[fieldNameOnTargetRecord]: (targetRecordFieldValue, { toReference }) => {
const fieldValueIsObjectRecordConnectionWithRefs =
isObjectRecordConnectionWithRefs(
sourceObjectNameSingular,
targetRecordFieldValue,
);
const sourceRecordReference = toReference({
id: sourceRecordId,
__typename: sourceRecordTypeName,
});
if (!isDefined(sourceRecordReference)) {
return targetRecordFieldValue;
}
if (fieldValueIsObjectRecordConnectionWithRefs) {
const nextEdges: RecordGqlRefEdge[] = [
...targetRecordFieldValue.edges,
{
__typename: `${sourceRecordTypeName}Edge`,
node: sourceRecordReference,
cursor: '',
},
];
return {
...targetRecordFieldValue,
edges: nextEdges,
};
} else {
// To one object => attach next relation record
return sourceRecordReference;
}
},
},
});
};