前回のおさらい
Gatsby は Node.js 製の Static Site Generator です。JSON ファイルのようなデータ構造からも静的ファイルを生成する事ができます。 今回は WebAPI から fetch する方法を紹介します。
前々回、前回と違い外部API から resouce を取得して Gatsby の node を生成する plugin は v1.5.3
時点でまだ存在しません。その為自身でこれらの処理を記述する必要があります。
準備
プロジェクトを作成します。
gatsby new practice-gatsby-http && cd $_ yarn add node-fetch touch gatsby-node.js
今回使用する WebAPI ですが、面倒なので http://jsonplaceholder.typicode.com/posts をそのまま使用します。
gatsby-node.js に sourceNodes 関数を追加します。sourceNodes に関しての詳しい説明は以下のページをご覧ください。
https://www.gatsbyjs.org/docs/node-apis/#sourceNodes
sourceNodes 関数
nodes 生成時に必要なデータをファイルから読み込む為に gatsby-node.js
に以下の処理を追記します。
yarn add node-fetch
gatsby-node.js
を修正します。
const crypto = require('crypto'); const _ = require(`lodash`); exports.sourceNodes = async ({ boundActionCreators }) => { const { createNode } = boundActionCreators const posts = await fetch("http://jsonplaceholder.typicode.com/posts?_limit=20").then(res => res.json()) // Process data into nodes. posts.forEach((post) => { createNode({ post, id: post.id + "", children: [], parent: "posts", internal: { type: "posts", content: JSON.stringify(post), contentDigest: crypto .createHash(`md5`) .update(JSON.stringify(post)) .digest(`hex`), } }) }) return }
動作確認
GraphiQL で allPosts と posts クエリーをそれぞれ発行する
query { allPosts { edges { node { id post { id title body } } } } }
query { posts(id: {eq: "1"}) { post { id title body } } }
まとめ
というわけで3回に渡って Gatsby の主幹となる nodes を生成する処理について紹介しました。実際に Page を生成するにはも少しステップが必要なのですがまた気が向いた時に tutorial でも作りたいと思います。