diff --git a/src/http/request.ts b/src/http/request.ts index 0a478911..7d8855aa 100644 --- a/src/http/request.ts +++ b/src/http/request.ts @@ -66,7 +66,8 @@ function shouldRetry(err: any, attempt: number, options: any) { // By default `retry.shouldRetry` doesn't retry on server errors so we add our own logic. const isSafe = options.method === 'GET' || options.method === 'HEAD' - const isQuery = options.uri.startsWith('/data/query') + const uri = options.uri || options.url + const isQuery = uri.startsWith('/data/query') const isRetriableResponse = err.response && (err.response.statusCode === 429 || diff --git a/test/client.test.ts b/test/client.test.ts index 7e104b02..93fafc09 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -13,7 +13,7 @@ import { } from '@sanity/client' import {of as observableOf} from 'rxjs' import {filter} from 'rxjs/operators' -import {describe, expect, test} from 'vitest' +import {describe, expect, test, vi} from 'vitest' const apiHost = 'api.sanity.url' const defaultProjectId = 'bf1942' @@ -335,6 +335,33 @@ describe('client', async () => { }) expect(client.projects.getById('n1f7y')).rejects.toBeDefined() }) + + test.each([429, 502, 503])('retries requests %d', async (code) => { + const userObj = { + role: null, + id: 'pabc123', + name: 'Mannen i Gata', + email: 'some@email.com', + } + + for (let i = 0; i < 5; i++) { + nock(`https://${apiHost}`).get('/v2023-03-25/users/me').reply(code, {}) + nock(`https://${apiHost}`).get('/v2023-03-25/users/me').reply(code, {}) + nock(`https://${apiHost}`).get('/v2023-03-25/users/me').reply(code, {}) + nock(`https://${apiHost}`).get('/v2023-03-25/users/me').reply(code, {}) + nock(`https://${apiHost}`).get('/v2023-03-25/users/me').reply(200, userObj) + } + + const fn = vi.fn().mockReturnValue(100) + const client = createClient({ + apiVersion: '2023-03-25', + useProjectHostname: false, + apiHost: `https://${apiHost}`, + retryDelay: fn, + }) + await expect(client.request({url: '/users/me'})).resolves.toEqual(userObj) + expect(fn).toHaveBeenCalledTimes(4) + }) }) describe('DATASETS', () => {