generate-graphql-docs.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import fs from 'fs';
  2. import {
  3. buildClientSchema,
  4. GraphQLField,
  5. GraphQLInputObjectType,
  6. GraphQLNamedType,
  7. GraphQLObjectType,
  8. GraphQLType,
  9. GraphQLUnionType,
  10. isEnumType,
  11. isInputObjectType,
  12. isNamedType,
  13. isObjectType,
  14. isScalarType,
  15. isUnionType,
  16. } from 'graphql';
  17. import path from 'path';
  18. import { deleteGeneratedDocs, generateFrontMatter } from './docgen-utils';
  19. // tslint:disable:no-console
  20. type TargetApi = 'shop' | 'admin';
  21. const targetApi: TargetApi = getTargetApiFromArgs();
  22. // The path to the introspection schema json file
  23. const SCHEMA_FILE = path.join(__dirname, `../../schema-${targetApi}.json`);
  24. // The absolute URL to the generated api docs section
  25. const docsUrl = `/docs/graphql-api/${targetApi}/`;
  26. // The directory in which the markdown files will be saved
  27. const outputPath = path.join(__dirname, `../../docs/content/docs/graphql-api/${targetApi}`);
  28. const enum FileName {
  29. ENUM = 'enums',
  30. INPUT = 'input-types',
  31. MUTATION = 'mutations',
  32. QUERY = 'queries',
  33. OBJECT = 'object-types',
  34. }
  35. const schemaJson = fs.readFileSync(SCHEMA_FILE, 'utf8');
  36. const parsed = JSON.parse(schemaJson);
  37. const schema = buildClientSchema(parsed.data ? parsed.data : parsed);
  38. deleteGeneratedDocs(outputPath);
  39. generateGraphqlDocs(outputPath);
  40. function generateGraphqlDocs(hugoOutputPath: string) {
  41. const timeStart = +new Date();
  42. let queriesOutput = generateFrontMatter('Queries', 1) + `\n\n# Queries\n\n`;
  43. let mutationsOutput = generateFrontMatter('Mutations', 2) + `\n\n# Mutations\n\n`;
  44. let objectTypesOutput = generateFrontMatter('Types', 3) + `\n\n# Types\n\n`;
  45. let inputTypesOutput = generateFrontMatter('Input Objects', 4) + `\n\n# Input Objects\n\n`;
  46. let enumsOutput = generateFrontMatter('Enums', 5) + `\n\n# Enums\n\n`;
  47. for (const type of Object.values(schema.getTypeMap())) {
  48. if (type.name.substring(0, 2) === '__') {
  49. // ignore internal types
  50. continue;
  51. }
  52. if (isObjectType(type)) {
  53. if (type.name === 'Query') {
  54. for (const field of Object.values(type.getFields())) {
  55. if (field.name === 'temp__') {
  56. continue;
  57. }
  58. queriesOutput += `## ${field.name}\n`;
  59. queriesOutput += renderDescription(field);
  60. queriesOutput += renderFields([field], false) + '\n\n';
  61. }
  62. } else if (type.name === 'Mutation') {
  63. for (const field of Object.values(type.getFields())) {
  64. mutationsOutput += `## ${field.name}\n`;
  65. mutationsOutput += renderDescription(field);
  66. mutationsOutput += renderFields([field], false) + '\n\n';
  67. }
  68. } else {
  69. objectTypesOutput += `## ${type.name}\n\n`;
  70. objectTypesOutput += renderDescription(type);
  71. objectTypesOutput += renderFields(type);
  72. objectTypesOutput += `\n`;
  73. }
  74. }
  75. if (isEnumType(type)) {
  76. enumsOutput += `## ${type.name}\n\n`;
  77. enumsOutput += renderDescription(type) + '\n\n';
  78. enumsOutput += '{{% gql-enum-values %}}\n';
  79. for (const value of type.getValues()) {
  80. enumsOutput += value.description ? ` * *// ${value.description.trim()}*\n` : '';
  81. enumsOutput += ` * ${value.name}\n`;
  82. }
  83. enumsOutput += '{{% /gql-enum-values %}}\n';
  84. enumsOutput += '\n';
  85. }
  86. if (isScalarType(type)) {
  87. objectTypesOutput += `## ${type.name}\n\n`;
  88. objectTypesOutput += renderDescription(type);
  89. }
  90. if (isInputObjectType(type)) {
  91. inputTypesOutput += `## ${type.name}\n\n`;
  92. inputTypesOutput += renderDescription(type);
  93. inputTypesOutput += renderFields(type);
  94. inputTypesOutput += `\n`;
  95. }
  96. if (isUnionType(type)) {
  97. objectTypesOutput += `## ${type.name}\n\n`;
  98. objectTypesOutput += renderDescription(type);
  99. objectTypesOutput += renderUnion(type);
  100. }
  101. }
  102. fs.writeFileSync(path.join(hugoOutputPath, FileName.QUERY + '.md'), queriesOutput);
  103. fs.writeFileSync(path.join(hugoOutputPath, FileName.MUTATION + '.md'), mutationsOutput);
  104. fs.writeFileSync(path.join(hugoOutputPath, FileName.OBJECT + '.md'), objectTypesOutput);
  105. fs.writeFileSync(path.join(hugoOutputPath, FileName.INPUT + '.md'), inputTypesOutput);
  106. fs.writeFileSync(path.join(hugoOutputPath, FileName.ENUM + '.md'), enumsOutput);
  107. console.log(`Generated 5 GraphQL API docs in ${+new Date() - timeStart}ms`);
  108. }
  109. /**
  110. * Renders the type description if it exists.
  111. */
  112. function renderDescription(type: { description?: string | null }): string {
  113. if (!type.description) {
  114. return '';
  115. }
  116. // Strip any JSDoc tags which may be used to annotate the generated
  117. // TS types.
  118. const stringsToStrip = [
  119. /@docsCategory\s+[^\n]+/g,
  120. /@description\s+/g,
  121. ];
  122. let result = type.description;
  123. for (const pattern of stringsToStrip) {
  124. result = result.replace(pattern, '');
  125. }
  126. return result + '\n\n';
  127. }
  128. function renderFields(
  129. typeOrFields: (GraphQLObjectType | GraphQLInputObjectType) | Array<GraphQLField<any, any>>,
  130. includeDescription = true,
  131. ): string {
  132. let output = '{{% gql-fields %}}\n';
  133. const fieldsArray: Array<GraphQLField<any, any>> = Array.isArray(typeOrFields)
  134. ? typeOrFields
  135. : Object.values(typeOrFields.getFields());
  136. for (const field of fieldsArray) {
  137. if (includeDescription) {
  138. output += field.description ? `* *// ${field.description.trim()}*\n` : '';
  139. }
  140. output += ` * ${renderFieldSignature(field)}\n`;
  141. }
  142. output += '{{% /gql-fields %}}\n\n';
  143. return output;
  144. }
  145. function renderUnion(type: GraphQLUnionType): string {
  146. const unionTypes = type.getTypes().map(t => renderTypeAsLink(t)).join(' | ');
  147. let output = '{{% gql-fields %}}\n';
  148. output += `union ${type.name} = ${unionTypes}\n`;
  149. output += '{{% /gql-fields %}}\n\n';
  150. return output;
  151. }
  152. /**
  153. * Renders a field signature including any argument and output type
  154. */
  155. function renderFieldSignature(field: GraphQLField<any, any>): string {
  156. let name = field.name;
  157. if (field.args && field.args.length) {
  158. name += `(${field.args.map(arg => arg.name + ': ' + renderTypeAsLink(arg.type)).join(', ')})`;
  159. }
  160. return `${name}: ${renderTypeAsLink(field.type)}`;
  161. }
  162. /**
  163. * Renders a type as a markdown link.
  164. */
  165. function renderTypeAsLink(type: GraphQLType): string {
  166. const innerType = unwrapType(type);
  167. const fileName = isEnumType(innerType)
  168. ? FileName.ENUM
  169. : isInputObjectType(innerType)
  170. ? FileName.INPUT
  171. : FileName.OBJECT;
  172. const url = `${docsUrl}${fileName}#${innerType.name.toLowerCase()}`;
  173. return type.toString().replace(innerType.name, `[${innerType.name}](${url})`);
  174. }
  175. /**
  176. * Unwraps the inner type from a higher-order type, e.g. [Address!]! => Address
  177. */
  178. function unwrapType(type: GraphQLType): GraphQLNamedType {
  179. if (isNamedType(type)) {
  180. return type;
  181. }
  182. let innerType = type;
  183. while (!isNamedType(innerType)) {
  184. innerType = innerType.ofType;
  185. }
  186. return innerType;
  187. }
  188. function getTargetApiFromArgs(): TargetApi {
  189. const apiArg = process.argv.find(arg => /--api=(shop|admin)/.test(arg));
  190. if (!apiArg) {
  191. console.error(`\nPlease specify which GraphQL API to generate docs for: --api=<shop|admin>\n`);
  192. process.exit(1);
  193. return null as never;
  194. }
  195. return apiArg === '--api=shop' ? 'shop' : 'admin';
  196. }