ふんばりフロントエンジニアのブログ

新米フロントエンジニアの備忘録です。ふんばり温泉タオル欲しい...

GraphQL+AppSyncで「currentObservable.query.getCurrentResult is not a function」と出た時の対処法

GraphQL使い始めてみたのですが、結構つまづいたのでメモ。

GraphQLクライアントとして「Apollo」を使ってみたのですが、素直に使うとどうやらappsyncとはあまり相性がよくなさそう。

解決方法

aws-appsync」を使わず、一からApollo Clientを作成する

詳細

基本的な使い方は下記のような感じでApollo Clientを作成して使用する方法だと思います。

import awsmobile from "./aws-exports"; //appsyncの設定ファイル
import AWSAppSyncClient from "aws-appsync";

const client = new AWSAppSyncClient({
    url: awsmobile.aws_appsync_graphqlEndpoint,
    region: awsmobile.aws_project_region,
    auth: {
        type: awsmobile.aws_appsync_authenticationType,
        apiKey: awsmobile.aws_appsync_apiKey,
    }
});

「おお、まとまっててええやんけ!」と思ったのですが、useQueryを使うと「currentObservable.query.getCurrentResult is not a function」のエラーが...

早速検索したところ下記の記事がヒットしました。

github.com

なるほど、依存関係を明示的に解決する方法があるのかと下記をpackage.jsonに追加しました。

"resolutions": {
    "apollo-client": "2.6.4"
  },

しかし、これを追加したところuseQueryは動くけどuseMutationは使えないというバグに出くわしました。

改めて調べてみたところ、これらのバグは「aws-appsync」が古い「apollo client」を参照しているため起こるバグのようです。

stackoverflow.com

上記に沿ってApollo Clientを一から作成する方法を取ってみました。

import awsmobile from "./aws-exports"; //appsyncの設定ファイル
import { ApolloLink } from 'apollo-link';
import ApolloClient from 'apollo-client';
import { createAuthLink } from 'aws-appsync-auth-link';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from "apollo-cache-inmemory";

const url = awsmobile.aws_appsync_graphqlEndpoint;
const region = awsmobile.aws_appsync_region;
const auth = {
  type: awsmobile.aws_appsync_authenticationType,
  apiKey: awsmobile.aws_appsync_apiKey
};
const link = ApolloLink.from([
    createAuthLink({ url, region, auth }),
    createHttpLink({ uri: url })
]);
const client = new ApolloClient({
    link,
    cache: new InMemoryCache(),
});


Apollo Clientの初期化は長くなりましたが、AppSyncとApolloを使うにはこうするしかなさそう...

早くアップデートしてもらえるといいなあ