Skip to content

Commit

Permalink
fix: unify retry interface (#130)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats authored Aug 31, 2023
1 parent 926bcfa commit 64e4aff
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
1 change: 1 addition & 0 deletions src/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class MicrolinkError extends Error {

const got = async (url, opts) => {
try {
if (opts.retry > 0) opts.retry = opts.retry + 1
if (opts.timeout === undefined) opts.timeout = false
const response = await ky(url, opts)
const body = await response.json()
Expand Down
6 changes: 1 addition & 5 deletions src/factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const factory = ({ VERSION, MicrolinkError, urlHttp, got, flatten }) => {
}, {})
}

const fetchFromApi = async (apiUrl, opts = {}, retryCount = 0) => {
const fetchFromApi = async (apiUrl, opts = {}) => {
try {
const response = await got(apiUrl, opts)
return opts.responseType === 'buffer'
Expand All @@ -73,10 +73,6 @@ const factory = ({ VERSION, MicrolinkError, urlHttp, got, flatten }) => {
? rawBody
: parseBody(isBodyBuffer ? rawBody.toString() : rawBody, err, uri)

if (body.code === 'EFATALCLIENT' && retryCount++ < 2) {
return fetchFromApi(apiUrl, opts, retryCount)
}

throw new MicrolinkError({
...body,
message: body.message,
Expand Down
11 changes: 10 additions & 1 deletion test/error/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,20 @@ clients.forEach(({ constructor: mql, target }) => {
})

test(`${target} » EFATALCLIENT`, async t => {
let count = 0

const hooks = {
beforeRetry: [
() => ++count
]
}

const error = await t.throwsAsync(
mql('https://example.com', { endpoint: 'https://notexist.dev' }),
mql('https://example.com', { endpoint: 'https://notexist.dev', retry: 3 }, { hooks }),
{ instanceOf: mql.MicrolinkError }
)

t.is(count, 3)
t.true(error.url === 'https://notexist.dev?url=https%3A%2F%2Fexample.com')
t.true(error.code === 'EFATALCLIENT')
t.true(error.status === 'error')
Expand Down

1 comment on commit 64e4aff

@vercel
Copy link

@vercel vercel bot commented on 64e4aff Aug 31, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.