如果您想知道如何拥有多个数据源以及多个 dataProvider 类型,即 rest、GraphQL 等v3 文档说明:
在 react-admin v2 中,数据提供者曾经是函数,而不是对象。React-admin v3 可以检测遗留数据提供者并在其周围包裹一个对象。因此,为 react-admin v2 开发的数据提供程序仍然可以与 react-admin v3 一起使用。
这意味着<Admin>
组件上的 dataProvider 属性可以采用:
- DataProvider 类型的对象
- 提供(类型、资源、参数)返回包含数据的Promise的函数。
这意味着,如果您提供的 DataProvider 是一个函数,则您必须创建一个适配器并手动调用您的提供者上的函数。这是一个例子。
./dataProviders.js
import { gqlDataProvider, restGQLDataProvider, restProvider } from './buildDataProviders';
// The first assumption is that all resources are unique, thus we can use an object or a map instead of an array. Key = resource, value = DataProvider.
const dataProviders = new Map([
['users', restGQLDataProvider],
['users-local', restProvider],
['Invoice', gqlDataProvider],
['Debtor', gqlDataProvider],
['Status', gqlDataProvider]
]);
export default async (type, resource, params) => {
// Get the DataProvider from the map.
const dataProvider = await dataProviders.get(resource);
// The DataProvider object is wrapped in a function so we can pass in the parameters to get the result.
if (dataProvider instanceof Function) {
return dataProvider(type, resource, params);
}
};
./buildDataProvider.js
import { gql } from 'apollo-boost';
import buildGraphQLProvider from 'ra-data-graphql-simple';
import { gqlClient, restClient } from './apolloClients';
import simpleRestProvider from 'ra-data-simple-rest';
const LOCAL_REST_ENDPOINT = 'http://localhost:3001/api';
export RestProvider = simpleRestProvider(LOCAL_REST_ENDPOINT);
export const gqlDataProvider = buildGraphQLProvider({
client: gqlClient
});
// This is just an example of the getList provider, you'll have to write the rest.
export const restProvider = (type, resource, params) => {
const providerMap = new Map([
['GET_LIST', async () => {
return await RestProvider.getList(resource, params);
}]
])
export const restGQLDataProvider = (type, resource, params) => {
const providerMap = new Map([
['GET_LIST', async () => {
const query = gql`
query ${resource} {
${resource} @rest(type: "${resource}", path: "/${resource}") {
id
name
username
email
address
phone
website
company
}
}
`;
const result = await restClient.query({ query });
return { data: result.data[resource], total: result.data[resource].length };
}]
])
}
./apolloClients.js
import { ApolloClient, ApolloLink, InMemoryCache, HttpLink } from 'apollo-boost';
import { RestLink } from 'apollo-link-rest';
import auth from '../../auth';
const GRAPHQL_ENDPOINT = 'http://localhost:4000';
const REST_ENDPOINT = 'http://jsonplaceholder.typicode.com';
const httpLink = new HttpLink({ uri: GRAPHQL_ENDPOINT });
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
'x-api-key': auth.aws_appsync_apiKey
}
});
return forward(operation);
});
export const restClient = new ApolloClient({
link: new RestLink({ uri: REST_ENDPOINT }),
cache: new InMemoryCache()
});
export const gqlClient = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});