Browse Source

feat(docs): Add support for union types in GraphQL doc gen

Michael Bromley 6 years ago
parent
commit
7cdcb0dea8

+ 18 - 2
codegen/generate-api-docs.ts

@@ -6,11 +6,13 @@ import {
     GraphQLNamedType,
     GraphQLObjectType,
     GraphQLType,
+    GraphQLUnionType,
     isEnumType,
     isInputObjectType,
     isNamedType,
     isObjectType,
     isScalarType,
+    isUnionType,
 } from 'graphql';
 import path from 'path';
 
@@ -105,6 +107,12 @@ function generateApiDocs(hugoOutputPath: string) {
             inputTypesOutput += renderFields(type);
             inputTypesOutput += `\n`;
         }
+
+        if (isUnionType(type)) {
+            objectTypesOutput += `## ${type.name}\n\n`;
+            objectTypesOutput += renderDescription(type);
+            objectTypesOutput += renderUnion(type);
+        }
     }
 
     fs.writeFileSync(path.join(hugoOutputPath, FileName.QUERY + '.md'), queriesOutput);
@@ -141,6 +149,14 @@ function renderFields(
     return output;
 }
 
+function renderUnion(type: GraphQLUnionType): string {
+    const unionTypes = type.getTypes().map(t => renderTypeAsLink(t)).join(' | ');
+    let output = '{{% gql-fields %}}\n';
+    output += `union ${type.name} = ${unionTypes}\n`;
+    output += '{{% /gql-fields %}}\n\n';
+    return output;
+}
+
 /**
  * Renders a field signature including any argument and output type
  */
@@ -160,8 +176,8 @@ function renderTypeAsLink(type: GraphQLType): string {
     const fileName = isEnumType(innerType)
         ? FileName.ENUM
         : isInputObjectType(innerType)
-        ? FileName.INPUT
-        : FileName.OBJECT;
+            ? FileName.INPUT
+            : FileName.OBJECT;
     const url = `${docsUrl}${fileName}#${innerType.name.toLowerCase()}`;
     return type.toString().replace(innerType.name, `[${innerType.name}](${url})`);
 }

+ 1 - 0
docs/assets/styles/_shortcodes.scss

@@ -63,6 +63,7 @@
  */
 .gql-fields {
     @include code-block;
+    font-family: 'Oxygen Mono', monospace;
     &::before {
         content: 'sdl';
         @include code-block-lang;

+ 2 - 1
server/src/api/schema/type/product-search.type.graphql

@@ -34,10 +34,11 @@ type SearchResult {
     facetValueIds: [String!]!
     "An array of ids of the Collections in which this result appears"
     collectionIds: [String!]!
-    "A relevence score for the result. Differs between database implementations."
+    "A relevence score for the result. Differs between database implementations"
     score: Float!
 }
 
+"The price of a search result product, either as a range or as a single price"
 union SearchResultPrice = PriceRange | SinglePrice
 
 "The price value where the result has a single price"