LoginSignup
3
0

More than 3 years have passed since last update.

GatsbyJS上からFirestoreのデータをGraphQLで引っ張ってくる方法

Last updated at Posted at 2020-11-23

GatsbyJSとFirebaseを連携させる上でどのプラグインを使ってどのように引っ張ってれば良いのかわからなかったので調べたまとめ
GatsbyJSとFirebaseは現時点では英語であっても情報がほとんどないと思うので必要な人もいると思うので記事にしました。備忘録も兼ねています。

※対象とする人は以下のため説明を簡略化している部分もあり
・Firebaseを一度は触ってホスティング又は、auth認証やFirestoreのデータを引っ張ったことがある人
・GatsbyJSやGraphQLを多少なりとも触ったことがある人

準備するもの

①gatsbyのプロジェクト作成
②gatsby-firesourceのインストール
③Firebase側でプロジェクト作成とFirebase Admin SDKの秘密鍵生成

①gatsbyのプロジェクト作成

不要物が少なくシンプルなHello Worldのみのスターターキットを引っ張ります

gatsby new gatsby-firebase https://github.com/gatsbyjs/gatsby-starter-hello-world
cd gatsby-firebase
gatsby develop

以下がコンソールに出力されればOKです。

You can now view gatsby-starter-hello-world in the browser.
⠀
  http://localhost:8000/
⠀
View GraphiQL, an in-browser IDE, to explore your site's data and schema
⠀
  http://localhost:8000/___graphql

②gatsby-firesourceのインストール

yarn add gatsby-firesource (もしくはnpm)

gatsby-source-firestore はメンテされておらずフロントエンドのUdemy講座で人気のTom Phillipsさんが推奨していないためgatsby-firesource(Tom氏が作成)を使います。

③Firebase側でプロジェクト作成とFirebase Admin SDKの秘密鍵生成

image.png

適当な名前をつけてあとは適当に進む
image.png

image.png

本番環境のままデータベースを作成
image.png

以下はコレクションを作成
image.png

ドキュメントIDは自動生成で今回はシンプルにするためフィールドは"name"と"email"だけにします。
image.png

次にFirebase Admin SDKの秘密鍵生成を生成します。
image.png

image.png

image.png

DLした秘密鍵をgatsby-firebaseのpackage.jsonと同階層の親ディレクトリに格納して名前を「firebase.json」へ改名します。
image.png

これで準備完了です。

gatsby-config.jsのファイルを編集する

plugin: [] の中に以下の内容を入力します。

    {
      resolve: 'gatsby-firesource', //プラグイン名
      options: {
        credential: require("./firebase.json"), //認証情報
        types: [
          {
            type: 'User', // GraphQL上で表示される名前
            collection: 'users', // 作成したコレクション名
            map: doc => ({ // ドキュメントデータ
              name: doc.name, // ドキュメントデータのフィールドname
              email: doc.email, // ドキュメントデータのフィールドemail
            }),
          },
        ],
      }
    }

再度、立ち上げます

gatsby develop

GraphQLへアクセスします。

http://localhost:8000/___graphql

画像のようにデータが拾えていたらOKです。もしデータが拾えてなかった場合はgatsby-config.jsのどこかが間違っているかFirestore側のドキュメントに誤りがある可能性があります。
image.png

あとはgatsby-node.jsやそれぞれのページでGraphQLを引っ張ってくればデータを勝手に扱えるようになりました。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0