📝
graphql-markdownの使い方
イントロダクション
graphql-markdownはGraphQLスキーマからマークダウンを出力し、docusaurusに食わせることでAPI仕様書を自動生成するツールです。
最初はspectaqlという別のツールを使っていて、それなりに良かったのですが、バグが多いのとメンテナンス頻度があまり高くないので、こちらのツールに乗り換えることにしました。
(結局、導入エラーにはまってめちゃくちゃ時間使ってしまったのですが。。。そのエラーと解決方法は後半でご紹介します。)
導入方法
公式ドキュメントを参考にdocusaurusとgraphql-markdownをセットアップしていきます。
sh
npm init docusaurus my-website https://github.com/graphql-markdown/template.git
適当に自分のGarphQLスキーマを用意します。
sh
cd my-wesite
touch schema.graphql
schema.graphql
type User {
"""
User's unique identifier
"""
id: ID!
"""
User's full name
"""
name: String!
"""
User's email address
"""
email: String!
"""
List of posts authored by this user
"""
posts: [Post!]
}
type Post {
id: ID!
title: String!
content: String!
author: User!
}
type Query {
getUser(id: ID!): User
getPosts: [Post!]!
}
ローカルファイルのスキーマを参照したいのでファイルローダーをインストールします
sh
npm install @graphql-tools/graphql-file-loader
先ほど作ったスキーマを参照するように.graphqlrc
を設定します。
.graphqlrc
schema: 'schema.graphql'
extensions:
graphql-markdown:
baseURL: '.'
homepage: 'static/index.md'
loaders:
GraphQLFileLoader: '@graphql-tools/graphql-file-loader'
docOptions:
frontMatter:
pagination_next: null
pagination_prev: null
printTypeOptions:
deprecated: 'group'
スキーマからマークダウンファイルを生成します。
sh
npm run doc
うまくいくと次のコマンドでdocusaurusサーバーがlocalhost:3000
に立ち上がります。
sh
npm run start
こんなエラーが出たら
npm run doc
時に以下のようなエラーが出てくる場合があります。
sh
[ERROR] Error: Cannot find module '@graphql-markdown/printer-legacy'.
at getPrinter (/Users/<username>/practice/my-website/node_modules/@graphql-markdown/core/dist/printer.js:41:15)
at async generateDocFromSchema (/Users/<username>/practice/my-website/node_modules/@graphql-markdown/core/dist/generator.js:42:21)
at async Command.<anonymous> (/Users/<username>/practice/my-website/node_modules/@graphql-markdown/docusaurus/dist/index.js:60:17)
この時は@graphql-markdown/docusaurus
プラグインを入れ直してあげるとエラーが治りました。
sh
npm install @graphql-markdown/docusaurus
また、次のようなメッセージが出てくる場合もありました。成功メッセージのように見えるのですが、実際にはMarkdownファイルは出力されていませんでした。
sh
[WARNING] An error occurred while processing "[object Object]"
[WARNING] An error occurred while processing "[object Object]"
[WARNING] An error occurred while processing "@include"
[WARNING] An error occurred while processing "@skip"
[WARNING] An error occurred while processing "@deprecated"
[WARNING] An error occurred while processing "@specifiedBy"
[WARNING] An error occurred while processing "@oneOf"
[WARNING] An error occurred while processing "User"
[WARNING] An error occurred while processing "Post"
[WARNING] An error occurred while processing "ID"
[WARNING] An error occurred while processing "String"
[WARNING] An error occurred while processing "Boolean"
[SUCCESS] Documentation successfully generated in "docs" with base URL ".".
[INFO] 12 pages generated in 0.084s from schema "test.graphql".
この時は次のようなコマンドで解決することができました。
sh
npm install @graphql-markdown/cli
npx gqlmd graphql-to-doc
背景
このエラーが全然解決できずに、色々試したりドキュメントを漁ったりした結果ver1.27のリリースノートにヒントがありました。
Discussion