-
Notifications
You must be signed in to change notification settings - Fork 2.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Refactor triggerUpdateRelationsOptimisticEffect
to compute relationship from Metadatas
#9815
Merged
prastoin
merged 17 commits into
main
from
9580-2-refactor-trigger-update-relations-optimistic-effect
Jan 24, 2025
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
45bff52
chore: to drop
prastoin 9451bea
refactor(front): consume metadatas to compute if current value is rec…
prastoin b09bdb1
chore: remove logs
prastoin cf640e6
chore(front): naming convention
prastoin bff83ee
refactor(front): avoid AHA
prastoin ceaf618
chore(front): remove unecessary optional access
prastoin 770c024
chore(front): todos wip
prastoin 7c6e995
chore(front): relocate hasManyTargetRecords
prastoin 8d6f5aa
refactor(front): remove redundant conditions
prastoin fcf12a6
refactor(front): handle ObjectRecord and not grapql record or connection
prastoin 97cec31
fix(front): tmp fix replace isEmpty by isArray
prastoin 398966d
chore(front): to review
prastoin 7bc75ce
chore(front): comment about RecordObject reflexion
prastoin 6fc76fa
test(front): isObjectRecordConnection
prastoin cca0c89
chore(front): remove comments and logs
prastoin 6e3e2ed
chore(front): update comment
prastoin afb243d
chore(front): typos and renaming
prastoin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,3 @@ | ||
import { ApolloCache } from '@apollo/client'; | ||
|
||
import { triggerAttachRelationOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerAttachRelationOptimisticEffect'; | ||
import { triggerDestroyRecordsOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerDestroyRecordsOptimisticEffect'; | ||
import { triggerDetachRelationOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerDetachRelationOptimisticEffect'; | ||
|
@@ -10,23 +8,26 @@ import { isObjectRecordConnection } from '@/object-record/cache/utils/isObjectRe | |
import { RecordGqlConnection } from '@/object-record/graphql/types/RecordGqlConnection'; | ||
import { RecordGqlNode } from '@/object-record/graphql/types/RecordGqlNode'; | ||
import { ObjectRecord } from '@/object-record/types/ObjectRecord'; | ||
import { ApolloCache } from '@apollo/client'; | ||
import { isArray } from '@sniptt/guards'; | ||
import { FieldMetadataType } from '~/generated-metadata/graphql'; | ||
import { isDeeplyEqual } from '~/utils/isDeeplyEqual'; | ||
import { isDefined } from '~/utils/isDefined'; | ||
|
||
type triggerUpdateRelationsOptimisticEffectArgs = { | ||
cache: ApolloCache<unknown>; | ||
sourceObjectMetadataItem: ObjectMetadataItem; | ||
currentSourceRecord: ObjectRecord | null; | ||
updatedSourceRecord: ObjectRecord | null; | ||
objectMetadataItems: ObjectMetadataItem[]; | ||
}; | ||
export const triggerUpdateRelationsOptimisticEffect = ({ | ||
cache, | ||
sourceObjectMetadataItem, | ||
currentSourceRecord, | ||
updatedSourceRecord, | ||
objectMetadataItems, | ||
}: { | ||
cache: ApolloCache<unknown>; | ||
sourceObjectMetadataItem: ObjectMetadataItem; | ||
currentSourceRecord: ObjectRecord | null; | ||
updatedSourceRecord: ObjectRecord | null; | ||
objectMetadataItems: ObjectMetadataItem[]; | ||
}) => { | ||
}: triggerUpdateRelationsOptimisticEffectArgs) => { | ||
return sourceObjectMetadataItem.fields.forEach( | ||
(fieldMetadataItemOnSourceRecord) => { | ||
const notARelationField = | ||
|
@@ -81,71 +82,55 @@ export const triggerUpdateRelationsOptimisticEffect = ({ | |
) { | ||
return; | ||
} | ||
const extractTargetRecordsFromRelation = ( | ||
value: RecordGqlConnection | RecordGqlNode | null, | ||
): RecordGqlNode[] => { | ||
// TODO investigate on the root cause of array injection here, should never occurs | ||
// Cache might be corrupted somewhere due to ObjectRecord and RecordGqlNode inclusion | ||
if (!isDefined(value) || isArray(value)) { | ||
return []; | ||
} | ||
|
||
// TODO: replace this by a relation type check, if it's one to many, | ||
// it's an object record connection (we can still check it though as a safeguard) | ||
const currentFieldValueOnSourceRecordIsARecordConnection = | ||
isObjectRecordConnection( | ||
targetObjectMetadata.nameSingular, | ||
currentFieldValueOnSourceRecord, | ||
); | ||
if (isObjectRecordConnection(relationDefinition, value)) { | ||
return value.edges.map(({ node }) => node); | ||
} | ||
|
||
const targetRecordsToDetachFrom = | ||
currentFieldValueOnSourceRecordIsARecordConnection | ||
? currentFieldValueOnSourceRecord.edges.map( | ||
({ node }) => node as RecordGqlNode, | ||
) | ||
: [currentFieldValueOnSourceRecord].filter(isDefined); | ||
return [value]; | ||
}; | ||
const targetRecordsToDetachFrom = extractTargetRecordsFromRelation( | ||
currentFieldValueOnSourceRecord, | ||
); | ||
const targetRecordsToAttachTo = extractTargetRecordsFromRelation( | ||
updatedFieldValueOnSourceRecord, | ||
); | ||
|
||
const updatedFieldValueOnSourceRecordIsARecordConnection = | ||
isObjectRecordConnection( | ||
targetObjectMetadata.nameSingular, | ||
updatedFieldValueOnSourceRecord, | ||
// TODO: see if we can de-hardcode this, put cascade delete in relation metadata item | ||
// Instead of hardcoding it here | ||
const shouldCascadeDeleteTargetRecords = | ||
CORE_OBJECT_NAMES_TO_DELETE_ON_TRIGGER_RELATION_DETACH.includes( | ||
targetObjectMetadata.nameSingular as CoreObjectNameSingular, | ||
); | ||
|
||
const targetRecordsToAttachTo = | ||
updatedFieldValueOnSourceRecordIsARecordConnection | ||
? updatedFieldValueOnSourceRecord.edges.map( | ||
({ node }) => node as RecordGqlNode, | ||
) | ||
: [updatedFieldValueOnSourceRecord].filter(isDefined); | ||
|
||
const shouldDetachSourceFromAllTargets = | ||
isDefined(currentSourceRecord) && targetRecordsToDetachFrom.length > 0; | ||
|
||
if (shouldDetachSourceFromAllTargets) { | ||
// TODO: see if we can de-hardcode this, put cascade delete in relation metadata item | ||
// Instead of hardcoding it here | ||
const shouldCascadeDeleteTargetRecords = | ||
CORE_OBJECT_NAMES_TO_DELETE_ON_TRIGGER_RELATION_DETACH.includes( | ||
targetObjectMetadata.nameSingular as CoreObjectNameSingular, | ||
); | ||
|
||
if (shouldCascadeDeleteTargetRecords) { | ||
triggerDestroyRecordsOptimisticEffect({ | ||
if (shouldCascadeDeleteTargetRecords) { | ||
triggerDestroyRecordsOptimisticEffect({ | ||
cache, | ||
objectMetadataItem: fullTargetObjectMetadataItem, | ||
recordsToDestroy: targetRecordsToDetachFrom, | ||
objectMetadataItems, | ||
}); | ||
} else if (isDefined(currentSourceRecord)) { | ||
targetRecordsToDetachFrom.forEach((targetRecordToDetachFrom) => { | ||
triggerDetachRelationOptimisticEffect({ | ||
cache, | ||
objectMetadataItem: fullTargetObjectMetadataItem, | ||
recordsToDestroy: targetRecordsToDetachFrom, | ||
objectMetadataItems, | ||
}); | ||
} else { | ||
targetRecordsToDetachFrom.forEach((targetRecordToDetachFrom) => { | ||
triggerDetachRelationOptimisticEffect({ | ||
cache, | ||
sourceObjectNameSingular: sourceObjectMetadataItem.nameSingular, | ||
sourceRecordId: currentSourceRecord.id, | ||
fieldNameOnTargetRecord: targetFieldMetadata.name, | ||
targetObjectNameSingular: targetObjectMetadata.nameSingular, | ||
targetRecordId: targetRecordToDetachFrom.id, | ||
}); | ||
sourceObjectNameSingular: sourceObjectMetadataItem.nameSingular, | ||
sourceRecordId: currentSourceRecord.id, | ||
fieldNameOnTargetRecord: targetFieldMetadata.name, | ||
targetObjectNameSingular: targetObjectMetadata.nameSingular, | ||
targetRecordId: targetRecordToDetachFrom.id, | ||
}); | ||
} | ||
}); | ||
} | ||
|
||
const shouldAttachSourceToAllTargets = | ||
isDefined(updatedSourceRecord) && targetRecordsToAttachTo.length > 0; | ||
|
||
if (shouldAttachSourceToAllTargets) { | ||
if (isDefined(updatedSourceRecord)) { | ||
targetRecordsToAttachTo.forEach((targetRecordToAttachTo) => | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remark: This could be an invariant, but implicitly quite though to tell |
||
triggerAttachRelationOptimisticEffect({ | ||
cache, | ||
|
51 changes: 31 additions & 20 deletions
51
...ty-front/src/modules/object-record/cache/utils/__tests__/isObjectRecordConnection.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,38 @@ | ||
import { peopleQueryResult } from '~/testing/mock-data/people'; | ||
|
||
import { FieldMetadataItem } from '@/object-metadata/types/FieldMetadataItem'; | ||
import { isObjectRecordConnection } from '@/object-record/cache/utils/isObjectRecordConnection'; | ||
|
||
import { RelationDefinitionType } from '~/generated-metadata/graphql'; | ||
describe('isObjectRecordConnection', () => { | ||
it('should work with query result', () => { | ||
const validQueryResult = peopleQueryResult.people; | ||
|
||
const isValidQueryResult = isObjectRecordConnection( | ||
'person', | ||
validQueryResult, | ||
); | ||
|
||
expect(isValidQueryResult).toEqual(true); | ||
}); | ||
const relationDefinitionMap: { [K in RelationDefinitionType]: boolean } = { | ||
[RelationDefinitionType.MANY_TO_MANY]: true, | ||
[RelationDefinitionType.ONE_TO_MANY]: true, | ||
[RelationDefinitionType.MANY_TO_ONE]: false, | ||
[RelationDefinitionType.ONE_TO_ONE]: false, | ||
}; | ||
|
||
it('should fail with invalid result', () => { | ||
const invalidResult = { test: 123 }; | ||
it.each(Object.entries(relationDefinitionMap))( | ||
'.$relation', | ||
(relation, expected) => { | ||
const emptyRecord = {}; | ||
const result = isObjectRecordConnection( | ||
{ | ||
direction: relation, | ||
} as NonNullable<FieldMetadataItem['relationDefinition']>, | ||
emptyRecord, | ||
); | ||
|
||
const isValidQueryResult = isObjectRecordConnection( | ||
'person', | ||
invalidResult, | ||
); | ||
expect(result).toEqual(expected); | ||
}, | ||
); | ||
|
||
expect(isValidQueryResult).toEqual(false); | ||
it('should throw on unknown relation direction', () => { | ||
const emptyRecord = {}; | ||
expect(() => | ||
isObjectRecordConnection( | ||
{ | ||
direction: 'UNKNOWN_TYPE', | ||
} as any, | ||
emptyRecord, | ||
), | ||
).toThrowError(); | ||
}); | ||
}); |
41 changes: 17 additions & 24 deletions
41
packages/twenty-front/src/modules/object-record/cache/utils/isObjectRecordConnection.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,23 @@ | ||
import { z } from 'zod'; | ||
|
||
import { FieldMetadataItem } from '@/object-metadata/types/FieldMetadataItem'; | ||
import { RecordGqlConnection } from '@/object-record/graphql/types/RecordGqlConnection'; | ||
import { capitalize } from 'twenty-shared'; | ||
import { assertUnreachable } from '@/workflow/utils/assertUnreachable'; | ||
import { RelationDefinitionType } from '~/generated-metadata/graphql'; | ||
|
||
export const isObjectRecordConnection = ( | ||
objectNameSingular: string, | ||
relationDefinition: NonNullable<FieldMetadataItem['relationDefinition']>, | ||
value: unknown, | ||
): value is RecordGqlConnection => { | ||
const objectConnectionTypeName = `${capitalize( | ||
prastoin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
objectNameSingular, | ||
)}Connection`; | ||
const objectEdgeTypeName = `${capitalize(objectNameSingular)}Edge`; | ||
|
||
const objectConnectionSchema = z.object({ | ||
__typename: z.literal(objectConnectionTypeName).optional(), | ||
edges: z.array( | ||
z.object({ | ||
__typename: z.literal(objectEdgeTypeName).optional(), | ||
node: z.object({ | ||
id: z.string().uuid(), | ||
}), | ||
}), | ||
), | ||
}); | ||
|
||
const connectionValidation = objectConnectionSchema.safeParse(value); | ||
|
||
return connectionValidation.success; | ||
switch (relationDefinition.direction) { | ||
case RelationDefinitionType.MANY_TO_MANY: | ||
case RelationDefinitionType.ONE_TO_MANY: { | ||
return true; | ||
} | ||
case RelationDefinitionType.MANY_TO_ONE: | ||
case RelationDefinitionType.ONE_TO_ONE: { | ||
return false; | ||
} | ||
default: { | ||
return assertUnreachable(relationDefinition.direction); | ||
} | ||
} | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remark: This could be an invariant, but implicitly quite though to tell
TypeScript