diff --git a/app/src/resources/runs/index.ts b/app/src/resources/runs/index.ts index 5c97434dd31..d1d84d3bc1b 100644 --- a/app/src/resources/runs/index.ts +++ b/app/src/resources/runs/index.ts @@ -29,3 +29,4 @@ export * from './useModuleCalibrationStatus' export * from './useProtocolAnalysisErrors' export * from './useLastRunCommand' export * from './useRunStatuses' +export * from './useUpdateRecoveryPolicyWithStrategy' diff --git a/app/src/resources/runs/useUpdateRecoveryPolicyWithStrategy.ts b/app/src/resources/runs/useUpdateRecoveryPolicyWithStrategy.ts new file mode 100644 index 00000000000..7720066c74e --- /dev/null +++ b/app/src/resources/runs/useUpdateRecoveryPolicyWithStrategy.ts @@ -0,0 +1,60 @@ +import { + useHost, + useUpdateErrorRecoveryPolicy, +} from '@opentrons/react-api-client' +import { getErrorRecoveryPolicy } from '@opentrons/api-client' + +import type { + HostConfig, + ErrorRecoveryPolicyResponse, + RecoveryPolicyRulesParams, +} from '@opentrons/api-client' + +/** + * append - Add a new policy rule to the end of the existing recovery policy. + */ +export type UpdatePolicyStrategy = 'append' + +export interface UpdateErrorRecoveryPolicyWithStrategy { + runId: string + newPolicy: RecoveryPolicyRulesParams[number] + strategy: UpdatePolicyStrategy +} + +export function useUpdateRecoveryPolicyWithStrategy( + runId: string +): ( + newPolicy: UpdateErrorRecoveryPolicyWithStrategy['newPolicy'], + strategy: UpdateErrorRecoveryPolicyWithStrategy['strategy'] +) => Promise { + const host = useHost() + + const { + mutateAsync: updateErrorRecoveryPolicy, + } = useUpdateErrorRecoveryPolicy(runId) + + return ( + newPolicy: UpdateErrorRecoveryPolicyWithStrategy['newPolicy'], + strategy: UpdateErrorRecoveryPolicyWithStrategy['strategy'] + ) => + getErrorRecoveryPolicy(host as HostConfig, runId).then(res => { + const existingPolicyRules = res.data.data.policyRules.map(rule => ({ + commandType: rule.matchCriteria.command.commandType, + errorType: rule.matchCriteria.command.error.errorType, + ifMatch: rule.ifMatch, + })) + + const buildUpdatedPolicy = (): RecoveryPolicyRulesParams => { + switch (strategy) { + case 'append': + return [...existingPolicyRules, newPolicy] + default: { + console.error('Handled policy strategy, using append.') + return [...existingPolicyRules, newPolicy] + } + } + } + + return updateErrorRecoveryPolicy(buildUpdatedPolicy()) + }) +}