以前に「GatsbyによるJSONからの一括生成を調べた」がGatsbyに慣れてなかったので、一通り習熟してから再チャレンジしている。 99nyorituryo.hatenablog.com
gatsby starter blogではフォルダ名がslugになっているが、そこをファイル名にできないかを調べていた。
markdownだとこう書けばいいのだが
exports.onCreateNode = ({ node }) => {
if (node.internal.type === MarkdownRemark
) {
console.log(node);
}
};
jsonだとどうすればいいのかがわからなかったので、
githubで検索
exports.onCreateNode = ({ node }) => {
if (node.internal.type === 'File' && node.internal.mediaType === 'application/json') {
console.log(createFilePath({ node, getNode, basePath: data
}))
}
}
};
Nodeは追加できたがAlljsonではなくallFileのほうに追加されていた。これで、slugをキーにしてjsonをファイルごとに取得できるのでは。
query MyQuery { allFile { edges { node { fields { slug } childrenJson { Asin Booktype Category Contributor ImageURL Points Price Publisher Title URL } } } } }
www.gatsbyjs.com
fileをslugで検索して絞り込んだ。jsonだとmarkdownと違ってfileのほうに追加されてしまうのがよくわからない。
export const query = graphql
query MyQuery($slug: String!) {
file(fields: {slug: { eq: $slug } }) {
childrenJson {
Asin
Booktype
Category
Contributor
ImageURL
Points
Price
Publisher
Title
URL
}
}
}
gatsbyのエラー処理、どうもファイルを読み込む前にqueryが実行されて、クエリがない状態が続く。エラー処理はgatsby starter blogを参考に見ていくとなんとなくわかったが、完全にはエラーが消えない。