Skip to content

Commit

Permalink
feat: retry fetching font metadata on network error (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
qwerzl authored Nov 18, 2024
1 parent d16cfce commit 960ab41
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
18 changes: 16 additions & 2 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,32 @@ interface Mini$FetchOptions extends RequestInit {
baseURL?: string
responseType?: 'json' | 'text'
query?: Record<string, any>
retries?: number
retryDelay?: number
}

function mini$fetch<T = unknown>(url: string, options?: Mini$FetchOptions) {
function mini$fetch<T = unknown>(url: string, options?: Mini$FetchOptions): Promise<T> {
if (options?.baseURL) {
url = options.baseURL + url
}
if (options?.query) {
const params = new URLSearchParams(options.query)
url = `${url}?${params.toString()}`
}

const retries = options?.retries ?? 3
const retryDelay = options?.retryDelay ?? 1000

return fetch(url, options)
.then(r => options?.responseType === 'json' ? r.json() : r.text()) as Promise<T>
.then(r => options?.responseType === 'json' ? r.json() : r.text())
.catch((err) => {
if (retries <= 0) {
throw err
}
console.warn(`Could not fetch from \`${url}\`. Will retry in \`${retryDelay}ms\`. \`${retries}\` retries left.`)
return new Promise(resolve => setTimeout(resolve, retryDelay))
.then(() => mini$fetch(url, { ...options, retries: retries - 1 }))
}) as Promise<T>
}

export const $fetch = Object.assign(mini$fetch, {
Expand Down
27 changes: 26 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
import { createUnifont, defineFontProvider } from '../src'
import { createUnifont, defineFontProvider, providers } from '../src'

describe('unifont', () => {
it('works with no providers', async () => {
Expand Down Expand Up @@ -48,4 +48,29 @@ describe('unifont', () => {
)
error.mockRestore()
})

it('retries on network errors', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
globalThis.fetch = vi.fn(() =>
Promise.reject(new Error('Network Error')),
)
const unifont = await createUnifont([
providers.google(),
])
const { fonts } = await unifont.resolveFont('Poppins')
expect(fonts).toMatchInlineSnapshot(`[]`)
expect(console.warn).toHaveBeenCalledTimes(3)
expect(console.warn).toHaveBeenNthCalledWith(1, 'Could not fetch from `https://fonts.google.com/metadata/fonts`. Will retry in `1000ms`. `3` retries left.')
expect(console.warn).toHaveBeenNthCalledWith(2, 'Could not fetch from `https://fonts.google.com/metadata/fonts`. Will retry in `1000ms`. `2` retries left.')
expect(console.warn).toHaveBeenNthCalledWith(3, 'Could not fetch from `https://fonts.google.com/metadata/fonts`. Will retry in `1000ms`. `1` retries left.')
expect(console.error).toHaveBeenCalledWith(
'Could not initialize provider `google`. `unifont` will not be able to process fonts provided by this provider.',
expect.objectContaining({}),
)
warn.mockRestore()
error.mockRestore()
// @ts-expect-error globalThis.fetch is altered
globalThis.fetch.mockRestore()
})
})

0 comments on commit 960ab41

Please sign in to comment.