import { AddComponentLabels, RemoveComponentLabels, } from '@atlassian/forge-graphql-types'; import { GqlSegment } from './types'; import generateMutationGql from '../generateMutationGql'; export default function updateLabelsSegment( componentId: string, oldLabels: Array = [], newLabels: Array = undefined, ): GqlSegment { let segmentAcc = { mutation: '', parameters: [] as Array, variables: {}, }; // if newLabels is null, remove existing labels if (newLabels === undefined) { return segmentAcc; } newLabels = newLabels || []; const labelsInBoth = oldLabels.filter((existingLabel) => newLabels.some((newLabel) => newLabel === existingLabel), ); const toBeAdded = newLabels.filter( (newLabel) => !labelsInBoth.some((overlapLabel) => newLabel === overlapLabel), ); const toBeRemoved = oldLabels.filter( (oldLabel) => !labelsInBoth.some((overlapLabel) => oldLabel === overlapLabel), ); if (toBeAdded.length > 0) { const { mutationGql: addLabelsMutation, params: addLabelsParams, inputId: addLabelsInputId, } = generateMutationGql(AddComponentLabels, 'addComponentLabels'); const variables = {} as Record; variables[addLabelsInputId] = { componentId, labelNames: toBeAdded, }; segmentAcc = { mutation: addLabelsMutation, parameters: addLabelsParams, variables, }; } if (toBeRemoved.length > 0) { const { mutationGql: removeLabelsMutation, params: removeLabelsParams, inputId: removeLabelsInputId, } = generateMutationGql(RemoveComponentLabels, 'removeComponentLabels'); const variables = {} as Record; variables[removeLabelsInputId] = { componentId, labelNames: toBeRemoved, }; segmentAcc = { mutation: segmentAcc.mutation + removeLabelsMutation, parameters: [...segmentAcc.parameters, ...removeLabelsParams], variables: { ...segmentAcc.variables, ...variables, }, }; } return segmentAcc; }