This repository was archived by the owner on Nov 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
Enhance/fetch base query #7
Merged
msutkowski
merged 11 commits into
rtk-incubator:main
from
themindoverall:enhance/fetch-base-query
Nov 8, 2020
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
7be4343
add params, headers, body options to fetchBaseQuery
themindoverall 820f34b
Fix relative URL joining
themindoverall 0bf7ee7
Add some simple tests for joinUrls behavior
msutkowski 5878327
Fix example, add sandbox config
msutkowski 4799282
Some PR feedback fixes, bogus impl in counter for testing
msutkowski 8b09896
Add network/parsing cases for evaluation to svelte example
msutkowski 6ef2702
Use isPlainObject from RTK
msutkowski 8490f0b
Fix import for QueryStatus
msutkowski 8ecea84
Update assertIsNewRTKPromise CSB build link
msutkowski a2d2f7a
Merge branch 'main' into enhance/fetch-base-query
msutkowski 066032c
Remove comment
msutkowski File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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'); | ||
msutkowski marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.