1
0

generate-api-docs.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. generateApiDocs(outputPath);
  40. function generateApiDocs(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 }, appendNewlines = true): string {
  113. return type.description ? `${type.description + (appendNewlines ? '\n\n' : '')}` : '';
  114. }
  115. function renderFields(
  116. typeOrFields: (GraphQLObjectType | GraphQLInputObjectType) | Array<GraphQLField<any, any>>,
  117. includeDescription = true,
  118. ): string {
  119. let output = '{{% gql-fields %}}\n';
  120. const fieldsArray: Array<GraphQLField<any, any>> = Array.isArray(typeOrFields)
  121. ? typeOrFields
  122. : Object.values(typeOrFields.getFields());
  123. for (const field of fieldsArray) {
  124. if (includeDescription) {
  125. output += field.description ? `* *// ${field.description.trim()}*\n` : '';
  126. }
  127. output += ` * ${renderFieldSignature(field)}\n`;
  128. }
  129. output += '{{% /gql-fields %}}\n\n';
  130. return output;
  131. }
  132. function renderUnion(type: GraphQLUnionType): string {
  133. const unionTypes = type.getTypes().map(t => renderTypeAsLink(t)).join(' | ');
  134. let output = '{{% gql-fields %}}\n';
  135. output += `union ${type.name} = ${unionTypes}\n`;
  136. output += '{{% /gql-fields %}}\n\n';
  137. return output;
  138. }
  139. /**
  140. * Renders a field signature including any argument and output type
  141. */
  142. function renderFieldSignature(field: GraphQLField<any, any>): string {
  143. let name = field.name;
  144. if (field.args && field.args.length) {
  145. name += `(${field.args.map(arg => arg.name + ': ' + renderTypeAsLink(arg.type)).join(', ')})`;
  146. }
  147. return `${name}: ${renderTypeAsLink(field.type)}`;
  148. }
  149. /**
  150. * Renders a type as a markdown link.
  151. */
  152. function renderTypeAsLink(type: GraphQLType): string {
  153. const innerType = unwrapType(type);
  154. const fileName = isEnumType(innerType)
  155. ? FileName.ENUM
  156. : isInputObjectType(innerType)
  157. ? FileName.INPUT
  158. : FileName.OBJECT;
  159. const url = `${docsUrl}${fileName}#${innerType.name.toLowerCase()}`;
  160. return type.toString().replace(innerType.name, `[${innerType.name}](${url})`);
  161. }
  162. /**
  163. * Unwraps the inner type from a higher-order type, e.g. [Address!]! => Address
  164. */
  165. function unwrapType(type: GraphQLType): GraphQLNamedType {
  166. if (isNamedType(type)) {
  167. return type;
  168. }
  169. let innerType = type;
  170. while (!isNamedType(innerType)) {
  171. innerType = innerType.ofType;
  172. }
  173. return innerType;
  174. }
  175. function getTargetApiFromArgs(): TargetApi {
  176. const apiArg = process.argv.find(arg => /--api=(shop|admin)/.test(arg));
  177. if (!apiArg) {
  178. console.error(`\nPlease specify which GraphQL API to generate docs for: --api=<shop|admin>\n`);
  179. process.exit(1);
  180. return null as never;
  181. }
  182. return apiArg === '--api=shop' ? 'shop' : 'admin';
  183. }