|
| 1 | +import { expect } from 'chai'; |
| 2 | +import apiCall from '../../../../server/lib/apiCall'; |
| 3 | + |
| 4 | +describe('apiCall', () => { |
| 5 | + it('should unwrap .data from the SDK v4 response', async () => { |
| 6 | + const user = { user_id: 'auth0|123', identities: [ { connection: 'Username-Password-Authentication' } ] }; |
| 7 | + const method = () => Promise.resolve({ data: user, status: 200, headers: {} }); |
| 8 | + |
| 9 | + const result = await apiCall({}, method, [ { id: 'auth0|123' } ]); |
| 10 | + |
| 11 | + expect(result).to.deep.equal(user); |
| 12 | + expect(result.identities).to.be.an('array'); |
| 13 | + expect(result.identities[0].connection).to.equal('Username-Password-Authentication'); |
| 14 | + }); |
| 15 | + |
| 16 | + it('should throw non-retryable errors immediately', async () => { |
| 17 | + const error = new Error('Not found'); |
| 18 | + error.originalError = { status: 404 }; |
| 19 | + const method = () => Promise.reject(error); |
| 20 | + |
| 21 | + try { |
| 22 | + await apiCall({}, method, []); |
| 23 | + expect.fail('Should have thrown'); |
| 24 | + } catch (err) { |
| 25 | + expect(err).to.equal(error); |
| 26 | + } |
| 27 | + }); |
| 28 | + |
| 29 | + it('should not retry when rate limit reset exceeds max retry timeout', async () => { |
| 30 | + const ratelimitReset = Math.round(Date.now() / 1000) + 100; |
| 31 | + const error = new Error('Rate limit'); |
| 32 | + error.originalError = { |
| 33 | + status: 429, |
| 34 | + response: { header: { 'x-ratelimit-reset': ratelimitReset } } |
| 35 | + }; |
| 36 | + const method = () => Promise.reject(error); |
| 37 | + |
| 38 | + try { |
| 39 | + await apiCall({}, method, []); |
| 40 | + expect.fail('Should have thrown'); |
| 41 | + } catch (err) { |
| 42 | + expect(err).to.equal(error); |
| 43 | + } |
| 44 | + }); |
| 45 | + |
| 46 | + it('should retry on 429 and resolve on success', async function() { |
| 47 | + this.timeout(5000); |
| 48 | + |
| 49 | + const user = { user_id: 'auth0|123', identities: [ { connection: 'Username-Password-Authentication' } ] }; |
| 50 | + const ratelimitReset = Math.round(Date.now() / 1000); |
| 51 | + const error = new Error('Rate limit'); |
| 52 | + error.originalError = { |
| 53 | + status: 429, |
| 54 | + response: { header: { 'x-ratelimit-reset': ratelimitReset } } |
| 55 | + }; |
| 56 | + |
| 57 | + let callCount = 0; |
| 58 | + const method = () => { |
| 59 | + callCount++; |
| 60 | + if (callCount === 1) return Promise.reject(error); |
| 61 | + return Promise.resolve({ data: user, status: 200, headers: {} }); |
| 62 | + }; |
| 63 | + |
| 64 | + const result = await apiCall({}, method, [], 2); |
| 65 | + |
| 66 | + expect(result).to.deep.equal(user); |
| 67 | + expect(callCount).to.equal(2); |
| 68 | + }); |
| 69 | +}); |
0 commit comments