我正在做一个项目,我们最终编写了自己的 dataProvider,因为我们的 api 并不是严格意义上的宁静。
这有点让人头疼,但是一旦你弄清楚了工作流程,它就不会太糟糕了。
基本上在调用 dataProvider 时会发生三件事
- dataProvider 使用参数调用 convertDataProviderRequestToHTTP,它返回一个 url 和用于发送 fetch/api 调用(构建请求)的选项
- fetch request/api 调用被发送(发送请求)
- dataProvider 返回调用 convertHTTPResponseToDataProvider 的结果,它将响应转换为对接收它的资源有用的东西(处理来自请求的响应)
这是 react-admin 文档相关部分的链接
https://marmelab.com/react-admin/DataProviders.html#writing-your-own-data-provider
我们的解决方案使用 switch 语句,其 case 是类型,然后每个 case 都有处理不同资源的逻辑。
我不确定这是否是预期的实现,但我们最终得到了这样的结果:
// import all the things
// set your api path prefix
const convertDataProviderRequestToHTTP = (type, resource, params) => {
//switch statement with one case for each action type
// and some logic where necessary for different resources ie.
switch(type){
case "GET_ONE":{
// if statements to handle resources with goofy endpoints
if(resource === 'abc/def'){
const url = `${API_PREFIX}/abc/def`;
const options = {
// set the specific options that you need for a
// each particular resource
}
}
// handles resources with normal restful endpoints
const url = `${API_PREFIX}/${RESOURCE}`;
const options = {
// this part depends on how you're doing your fetching
// might need to include the particular rest verb
// and any other settings
}
}
}
return {
url,
options
}
}
const convertHTTPResponseToDataProvider = (response, type, resource, params){
// another switch statement that converts the response that you get
// from your api to something that's useful to your Resource
switch(type){
case 'GET_ONE':{
if(resource === 'abc/def'){
// convert response into something useful and return it
return{
data: convertedResponse
}
}
}
}
}
export default (type, resource, params) => {
// this comes from react-admin, you could use plain old fetch or
// your favorite fetch library like axios instead
const { fetchJson } = fetchUtils;
// part 1, using the stuff that was sent in the dataProvider
// call to generate what you need to sending your fetch
const { url, options } = convertDataProviderRequestToHTTP(
type,
resource,
params
);
// add logic for grabbing your tokens and adding headers to options here
options.headers.set('headerkey', 'headervalue');
// part 2 sending the fetch request
return fetchJson(url, options).then(response =>
// part 3, converting the response and returning it
convertHTTPResponseToDataProvider(response, type, resource, params)
);
};
随着应用程序的发展,我们最终将其分解为单独的文件,以便更容易阅读,但到目前为止它似乎对我们来说还不错。
我必须安装 redux 浏览器工具并插入大量日志记录语句来逐步完成它,并更好地了解发生了什么以及何时发生。在获得第一个动作类型/资源组合后,它有点被点击并添加到它,从那时起就很容易弄清楚。