如何为Apollo单个Mutation延长超时并禁止重试?
Hey there, let's tackle your timeout and duplicate upload problems head-on. Here's how to adjust your Apollo Client setup to handle large 10MB JSON uploads properly:
1. Set a Custom Timeout for a Single Mutation
You can specify a longer timeout directly in the useMutation hook using the context option. This lets you override any global timeout settings just for this specific operation.
Here's how to implement it:
const [uploadLargeJson] = useMutation(YOUR_UPLOAD_MUTATION, { context: { // Set timeout to 60 seconds (adjust based on your needs) fetchOptions: { timeout: 60000 } }, // Add your existing onCompleted/onError handlers here });
This timeout value is in milliseconds, so 60000 equals 1 minute. This applies only to this mutation, leaving other operations using your default timeout settings.
2. Disable Retries for the Specific Mutation
Your current RetryLink is set to retry up to 5 times for any error, which is likely causing the duplicate uploads when the timeout hits. To stop this, we'll add a custom flag to the mutation's context and update the RetryLink to respect that flag.
First, modify your RetryLink configuration:
const retryLink = new RetryLink({ delay: { initial: 300, max: Infinity, jitter: true }, attempts: { max: 5, retryIf: (error, operation) => { // Check if the mutation has a "skipRetry" flag in its context const shouldSkipRetry = operation.getContext().skipRetry; // Only retry if there's an error AND the flag isn't set return !!error && !shouldSkipRetry; } }, });
Then, add the skipRetry flag to your useMutation call:
const [uploadLargeJson] = useMutation(YOUR_UPLOAD_MUTATION, { context: { fetchOptions: { timeout: 60000 }, skipRetry: true // This tells RetryLink to skip retries for this operation }, });
Now this mutation won't retry even if it hits a timeout or other error, preventing duplicate data from being sent to your database.
A Quick Note on Server-Side Timeouts
Don't forget to check your server's timeout settings too! If your backend or reverse proxy (like Nginx) has a shorter timeout than what you set on the client, it might still terminate the request early. Make sure those values are aligned with your client-side timeout to avoid unexpected issues.
内容的提问来源于stack exchange,提问作者Kevin Danikowski

