• Re-executes a function if a 409 response code is returned from commercetools

    When you make a request to update a resource in commercetools, you may receive a 409 response code if the resource has been updated since you last fetched it. This function will re-execute the function passed in to RetryOnConflictParams.executeFn in that scenario.

    You should retrieve the latest version of the resource before re-executing the function that caused the 409 response in the first place.

    For example, in order to update a product, you would first need to fetch the latest product (or product projection) and then post the update actions:

    import { retryOnConflict, CommercetoolsApi, Region } from '@gradientedge/commercetools-utils'

    const api = new CommercetoolsApi({
    projectKey: 'your-project-key',
    region: Region.EUROPE_GCP,
    clientId: 'your-client-id',
    clientSecret: 'your-client-secret',
    clientScopes: ['manage_products'],
    })

    const updatedProduct = await retryOnConflict({
    executeFn: async () => {
    // Get the latest product projection
    const productProjection = await api.getProductProjectionByKey({key: 'dummy-product-id'})

    // Attempt to update the product. If this fails with a 409, the function
    // will be retried, otherwise the `Product` object will be returned.
    return await api.updateProductById({
    id: productProjection.id,
    data: {
    version: productProjection.version,
    actions: [
    {
    action: 'setMetaTitle',
    metaTitle: {
    en: 'New meta title',
    },
    },
    ],
    },
    })
    },
    // The `executeFn` function will be called a maximum of 3 times (first attempt + 2 retries)
    maxRetries: 2,
    // The delay between for the first retry will be 20ms, increasing exponentially
    delayMs: 20,
    })

    console.log(updatedProduct)

    By default, the function passed in to RetryOnConflictParams.executeFn will be retried 3 times, though this can be altered by passing in a different value for the RetryOnConflictParams.maxRetries parameter.

    There is by default a 100ms delay after the first unsuccessful attempt, which is then increases exponentially for each subsequent attempt. This delay can be altered by passing in a different value for the RetryOnConflictParams.delayMs parameter.

    If the RetryOnConflictParams.jitter parameter is set to true, then a random element is added to the exponential increase in retry time.

    Type Parameters

    • T = any

    Parameters

    Returns Promise<T>