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