generate-api-docs.ts 6.8 KB

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