Skip to content
This repository was archived by the owner on Aug 28, 2024. It is now read-only.

feat: intercept requests #118

Merged
merged 2 commits into from
Jun 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/plenty-cooks-push.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@scalar/openapi-parser': patch
---

feat: intercept fetch requests
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,42 @@ describe('fetchUrlsPlugin', async () => {
it('returns false for undefinded', async () => {
expect(fetchUrlsPlugin().check()).toBe(false)
})

it('fetches the URL', async () => {
// @ts-expect-error only partially patched
global.fetch = async (url: string) => ({
text: async () => {
if (url === 'http://example.com/specification/openapi.yaml') {
return 'OK'
}

throw new Error('Not found')
},
})

expect(
await fetchUrlsPlugin().get(
'http://example.com/specification/openapi.yaml',
),
).toBe('OK')
})

it('rewrites the URL', async () => {
// @ts-expect-error only partially patched
global.fetch = async (url: string) => ({
text: async () => {
if (url === 'http://foobar.com/specification/openapi.yaml') {
return 'OK'
}

throw new Error('Not found')
},
})

expect(
await fetchUrlsPlugin({
fetch: (url) => fetch(url.replace('example', 'foobar')),
}).get('http://foobar.com/specification/openapi.yaml'),
).toBe('OK')
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@ export const fetchUrlsPluginDefaultConfiguration = {
}

export const fetchUrlsPlugin: (customConfiguration?: {
/**
* Limit the number of requests. Set to `false` to disable the limit.
*/
limit?: number | false
/**
* Fetch function to use instead of the global fetch. Use this to intercept requests.
*/
fetch?: (url: string) => Promise<Response>
}) => LoadPlugin = (customConfiguration) => {
// State
let numberOfRequests = 0
Expand Down Expand Up @@ -44,7 +51,10 @@ export const fetchUrlsPlugin: (customConfiguration?: {

try {
numberOfRequests++
const response = await fetch(value)

const response = await (configuration?.fetch
? configuration.fetch(value)
: fetch(value))

return await response.text()
} catch (error) {
Expand Down