-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add support for helpers in redux-thunk actions (#650)
Support for isomorphic `fetch` and `graphqlRequest` helpers in redux-thunk action creators
- Loading branch information
Showing
4 changed files
with
88 additions
and
23 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 |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import fetch from '../core/fetch'; | ||
|
||
function createGraphqlRequest(fetchKnowingCookie) { | ||
return async function graphqlRequest(query, variables) { | ||
const fetchConfig = { | ||
method: 'post', | ||
headers: { | ||
Accept: 'application/json', | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ query, variables }), | ||
credentials: 'include', | ||
}; | ||
const resp = await fetchKnowingCookie('/graphql', fetchConfig); | ||
if (resp.status !== 200) throw new Error(resp.statusText); | ||
return await resp.json(); | ||
}; | ||
} | ||
|
||
function createFetchKnowingCookie({ cookie }) { | ||
if (!process.env.BROWSER) { | ||
return (url, options = {}) => { | ||
const isLocalUrl = /^\/($|[^\/])/.test(url); | ||
|
||
// pass cookie only for itself. | ||
// We can't know cookies for other sites BTW | ||
if (isLocalUrl && options.credentials === 'include') { | ||
const headers = { | ||
...options.headers, | ||
cookie, | ||
}; | ||
return fetch(url, { ...options, headers }); | ||
} | ||
|
||
return fetch(url, options); | ||
}; | ||
} | ||
|
||
return fetch; | ||
} | ||
|
||
export default function createHelpers(config) { | ||
const fetchKnowingCookie = createFetchKnowingCookie(config); | ||
const graphqlRequest = createGraphqlRequest(fetchKnowingCookie); | ||
|
||
return { | ||
fetch: fetchKnowingCookie, | ||
graphqlRequest, | ||
}; | ||
} |