This repository has been archived by the owner on Jun 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Enhances `fetchBaseQuery` to have a more familiar API
- Loading branch information
1 parent
c65bc15
commit 8f84890
Showing
17 changed files
with
207 additions
and
57 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,3 @@ | ||
{ | ||
"template": "node" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,28 +1,65 @@ | ||
import { QueryApi } from './buildThunks'; | ||
import { joinUrls } from './utils'; | ||
import { isPlainObject } from '@reduxjs/toolkit'; | ||
|
||
interface FetchArgs extends RequestInit { | ||
url: string; | ||
params?: Record<string, any>; | ||
body?: any; | ||
responseHandler?: 'json' | 'text' | ((response: Response) => Promise<any>); | ||
validateStatus?: (response: Response, body: any) => boolean; | ||
} | ||
|
||
export function fetchBaseQuery({ baseUrl }: { baseUrl: string } = { baseUrl: '' }) { | ||
const defaultValidateStatus = (response: Response) => response.status >= 200 && response.status <= 299; | ||
|
||
const isJsonContentType = (headers: Headers) => headers.get('content-type')?.trim()?.startsWith('application/json'); | ||
|
||
export function fetchBaseQuery({ baseUrl }: { baseUrl?: string } = {}) { | ||
return async (arg: string | FetchArgs, { signal, rejectWithValue }: QueryApi) => { | ||
const { url, method = 'GET', ...rest } = typeof arg == 'string' ? { url: arg } : arg; | ||
const result = await fetch(`${baseUrl}/${url}`, { | ||
let { | ||
url, | ||
method = 'GET' as const, | ||
headers = undefined, | ||
body = undefined, | ||
params = undefined, | ||
responseHandler = 'json' as const, | ||
validateStatus = defaultValidateStatus, | ||
...rest | ||
} = typeof arg == 'string' ? { url: arg } : arg; | ||
let config: RequestInit = { | ||
method, | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
signal, | ||
body, | ||
...rest, | ||
}); | ||
}; | ||
|
||
config.headers = new Headers(headers); | ||
|
||
if (!config.headers.has('content-type')) { | ||
config.headers.set('content-type', 'application/json'); | ||
} | ||
|
||
if (body && isPlainObject(body) && isJsonContentType(config.headers)) { | ||
config.body = JSON.stringify(body); | ||
} | ||
|
||
if (params) { | ||
const divider = ~url.indexOf('?') ? '&' : '?'; | ||
const query = new URLSearchParams(params); | ||
url += divider + query; | ||
} | ||
|
||
url = joinUrls(baseUrl, url); | ||
|
||
const response = await fetch(url, config); | ||
|
||
let resultData = | ||
result.headers.has('Content-Type') && !result.headers.get('Content-Type')?.trim()?.startsWith('application/json') | ||
? await result.text() | ||
: await result.json(); | ||
const resultData = | ||
typeof responseHandler === 'function' | ||
? await responseHandler(response) | ||
: await response[responseHandler || 'text'](); | ||
|
||
return result.status >= 200 && result.status <= 299 | ||
return validateStatus(response, resultData) | ||
? resultData | ||
: rejectWithValue({ status: result.status, data: resultData }); | ||
: rejectWithValue({ status: response.status, data: resultData }); | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export * from './isAbsoluteUrl'; | ||
export * from './isValidUrl'; | ||
export * from './joinUrls'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
/** | ||
* If either :// or // is present consider it to be an absolute url | ||
* | ||
* @param url string | ||
*/ | ||
|
||
export function isAbsoluteUrl(url: string) { | ||
return new RegExp(`(^|:)//`).test(url); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
export function isValidUrl(string: string) { | ||
try { | ||
new URL(string); | ||
} catch (_) { | ||
return false; | ||
} | ||
|
||
return true; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import { isAbsoluteUrl } from '.'; | ||
|
||
const withoutTrailingSlash = (url: string) => url.replace(/\/$/, ''); | ||
const withoutLeadingSlash = (url: string) => url.replace(/^\//, ''); | ||
|
||
export function joinUrls(base: string | undefined, url: string | undefined): string { | ||
if (!base) { | ||
return url!; | ||
} | ||
if (!url) { | ||
return base; | ||
} | ||
|
||
if (isAbsoluteUrl(url)) { | ||
return url; | ||
} | ||
|
||
base = withoutTrailingSlash(base); | ||
url = withoutLeadingSlash(url); | ||
|
||
return `${base}/${url}`; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { joinUrls } from './joinUrls'; | ||
|
||
test('correctly joins variations relative urls', () => { | ||
expect(joinUrls('/api/', '/banana')).toBe('/api/banana'); | ||
expect(joinUrls('/api', '/banana')).toBe('/api/banana'); | ||
|
||
expect(joinUrls('/api/', 'banana')).toBe('/api/banana'); | ||
expect(joinUrls('/api/', '/banana/')).toBe('/api/banana/'); | ||
|
||
expect(joinUrls('/', '/banana/')).toBe('/banana/'); | ||
expect(joinUrls('/', 'banana/')).toBe('/banana/'); | ||
|
||
expect(joinUrls('/', '/banana')).toBe('/banana'); | ||
expect(joinUrls('/', 'banana')).toBe('/banana'); | ||
|
||
expect(joinUrls('', '/banana')).toBe('/banana'); | ||
expect(joinUrls('', 'banana')).toBe('banana'); | ||
}); | ||
|
||
test('correctly joins variations of absolute urls', () => { | ||
expect(joinUrls('https://apple.com', '/api/banana/')).toBe('https://apple.com/api/banana/'); | ||
expect(joinUrls('https://apple.com', '/api/banana')).toBe('https://apple.com/api/banana'); | ||
|
||
expect(joinUrls('https://apple.com/', 'api/banana/')).toBe('https://apple.com/api/banana/'); | ||
expect(joinUrls('https://apple.com/', 'api/banana')).toBe('https://apple.com/api/banana'); | ||
|
||
expect(joinUrls('https://apple.com/', 'api/banana/')).toBe('https://apple.com/api/banana/'); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters