首页 > 解决方案 > 将 ra-data-graphql 与 AppSync GraphQL API 一起使用

问题描述

我正在尝试将 react-admin 与 AWS Amplify 库和 AWS AppSync SDK 一起使用。

我不知道如何使用 ra-data-graphql/ra-data-graphql-simple 和 AWS AppSync API 来查询/更改数据。尝试使用 https://github.com/marmelab/react-admin/ 进行非常基本master/examples/demo测试

任何指导将不胜感激。

目前我正在尝试使用类似于下面的dataProvider:

src/dataProvider/appsync.js:

import gql from 'graphql-tag';
import AWSAppSyncClient, { AUTH_TYPE } from 'aws-appsync';
import buildGraphQLProvider, { buildQuery } from 'ra-data-graphql-simple';
import { __schema as schema } from './schema';

const client = new AWSAppSyncClient({
  url: "https://xxxx.appsync-api.us-east-1.amazonaws.com/graphql",
  region: "us-east-1,
  auth: {
    type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
    jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken(),
  }

const myBuildQuery = introspection => (fetchType, resource, params) => {
    const builtQuery = buildQuery(introspection)(fetchType, resource, params);

    if (resource === 'listings' && fetchType === 'GET_LIST') {
        return {
            ...builtQuery,
            query: gql`
                query getListings {
                    data: getListings {
                        items {
                            listingId
                        }
                    }
                }`,
        };
    }

    return builtQuery;
}

export default buildGraphQLProvider({ client: client, introspection: { schema }, buildQuery: myBuildQuery })

src/dataProvider/index.js:

export default type => {
    switch (type) {
        case 'graphql':
            return import('./graphql').then(factory => factory.default());
        case 'appsync':
            return import('./appsync');
        default:
            return import('./rest').then(provider => provider.default);
    }
};
src/App.js:

...
import dataProviderFactory from './dataProvider';
...

class App extends Component {
    state = { dataProvider: null };
    async componentDidMount() {
        const dataProvider = await dataProviderFactory(
            process.env.REACT_APP_DATA_PROVIDER
        );
        this.setState({ dataProvider });
    }
...
src/dashboard/Dashboard.js:

...
    fetchData() {
        this.fetchListings();
    }

    async fetchListings() {
        const { dataProvider } = this.props;
        const { data: reviews } = await dataProvider(GET_LIST, 'listings');
        console.log(listings)
    }
...

目前没有从 API 返回数据,并且在await dataProvider(GET_LIST, 'listings');说时抛出异常call: [object Model] is not a function,但是我看到 buildGraphQLProvider 承诺已成功解析为函数。

谁能建议我做错了什么以及完成任务的正确方法是什么?

标签: reactjsgraphqlaws-amplifyaws-appsyncreact-admin

解决方案


推荐阅读