查看 react 入门工具包中的 createHelpers.js 代码,我看到它在中间件中创建了一个 grapqlRequest 和一个 fetchKnowingCookie 方法。
https://github.com/kriasoft/react-starter-kit/blob/feature/redux/src/store/createHelpers.js
这究竟是在做什么?是否向服务器呈现的获取请求添加 cookie 标头?
我看到它还通过 将函数传递到中间件thunk.withExtraArgument
中,那条额外的行有什么作用?这是否意味着 fetch with cookies 功能可以从 redux 异步操作中获得?
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,
history: config.history,
};
}