首页 > 解决方案 > React Admin /通过'ra-data-graphql'库构建数据提供者 - 自动注入的'raFetchType'参数未定义

问题描述

我正在尝试通过创建一个 dataProvider ra-data-graphql,如库的 README中所述,并且成功地将自省响应传递给该buildQuery方法,但raFetchType 我的buildQuery方法中的参数始终未定义,并且应该发生的查询映射失败。看起来好像raFetchType应该由库自动填充,或者我(或文档)遗漏了一些东西。

buildCustomQuery注入时我需要提供一些额外的选项buildGraphQLProvider吗?

您所期望的: raFetchType已定义(我假设为“GET_LIST”、“GET_ONE”等之一)

相反发生了什么:(在库的源代码中调用)中 的raFetchType参数始终未定义buildQueryaorFetchType

相关代码:

// App.tsx

const [dataProvider, setDataProvider] = useState<DataProvider>();
const cache = new InMemoryCache();
const link = createHttpLink({
  uri: // my graphql API URL
});

const client = new ApolloClient({
  cache: cache,
  link: link,
});

useEffect(() => {
  buildGraphQLProvider({
    client: { client },
    buildQuery: buildCustomQuery,
    introspection: {
      schema, // JSON previously fetched from my GraphQL API
      operationNames: introspectionOperationNames, // function that maps the 'Country' resource to the correct query name for 'GET_LIST'
      include: ['Country'], // just trying it out with a single Resource first
    },
  }).then((dataProvider: any) => {
    setDataProvider(dataProvider);
  })
}, []);
// this is called via `buildGraphQLProvider` on init
export const buildCustomQuery = (introspectionResults: any) => (raFetchType: any, resourceName: any, params: any) => {
   // the introspectionResults contain the 4 properties listed here: https://github.com/marmelab/react-admin/tree/master/packages/ra-data-graphql#specify-your-queries-and-mutations
   // including the 'Country' resource with the mapped query name
   // however, `raFetchType` is undefined, and so no query can ever be returned. 
   // I get 'TypeError: Cannot read property 'parseResponse' of undefined' on ra-data-graphql/esm/index.js:113
    const resource = introspectionResults.resources.find((r: IntrospectionResource) => r.type.name === resourceName);
    switch (raFetchType) {
        case 'GET_LIST':
            return {
                query: gql`query ${resource[raFetchType].name}($id: ID) {
                    data: ${resource[raFetchType].name}(id: $id) {
                           ...
                        }
                    }
                }`,
                variables: params, // params = { id: ... }
                parseResponse: (response: any) => response.data,
            }
            break;
        // ... other types handled here
        default:
            return undefined;
    }
}

环境

标签: graphqlreact-admin

解决方案


推荐阅读