refactor existingRelationsReversed + doc

This commit is contained in:
Julie Plantey 2022-10-03 17:41:55 +02:00
parent 4e917068b1
commit fc6e4adbee
2 changed files with 19 additions and 8 deletions

View File

@ -195,6 +195,7 @@ export const RelationInputDataManger = ({
required={required}
searchResults={normalizeRelations(search, {
mainFieldName: mainField.name,
isSearch: true,
})}
size={size}
/>

View File

@ -22,25 +22,35 @@ const normalizeRelation = (relation, { shouldAddLink, mainFieldName, targetModel
return nextRelation;
};
/*
* Applies some transformations to existing and new relations in order to display them correctly
* relations: raw relations data coming from useRelations
* shouldAddLink: comes from generateRelationQueryInfos, if true we display a link to the relation (TO FIX: explanation)
* mainFieldName: name of the main field inside the relation (e.g. text field), if no displayable main field exists (e.g. date field) we use the id of the entry
* targetModel: the model on which the relation is based on, used to create an URL link
*/
export const normalizeRelations = (
relations,
{ modifiedData = {}, shouldAddLink = false, mainFieldName, targetModel }
{ modifiedData = {}, shouldAddLink = false, mainFieldName, targetModel, isSearch = false }
) => {
// To display oldest to newest relations we need to reverse each elements in array of results
// and reverse each arrays itself
const existingRelationsReversed = [...(relations?.data?.pages ?? [])]
.map((relation) => ({
...relation,
results: relation.results.slice().reverse(),
}))
.reverse();
const existingRelationsReversed = Array.isArray(relations?.data?.pages)
? relations?.data?.pages
.map((relation) => ({
...relation,
results: relation.results.slice().reverse(),
}))
.reverse()
: [];
return {
...relations,
data: {
pages:
[
...(targetModel ? existingRelationsReversed : relations?.data?.pages ?? []),
...(!isSearch ? existingRelationsReversed : relations?.data?.pages ?? []),
...(modifiedData?.connect ? [{ results: modifiedData.connect }] : []),
]
?.map((page) =>