Repository: graphql-markdown/graphql-markdown
Pull request #1294 (2024-02-15 18:13:03)

✨ (wip) support examples
# Description

Support examples using custom directive.

Initial implementation not for release.

# Checklist

- [x] My changes follow the [contributing guidelines](https://github.com/graphql-markdown/graphql-markdown/blob/main/CONTRIBUTING.md) of this project.
- [x] I have performed a self-review of my code.
- [x] I have made corresponding changes to the documentation.
- [x] I have added tests that prove my fix is effective or that my changes work.
- [x] New and existing unit tests pass locally with my changes.


sonarcloud[bot]: ## [![Quality Gate Failed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-failed-20px.png 'Quality Gate Failed')](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294) **Quality Gate failed**  
Failed conditions  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/failed-16px.png '') [6 New Major Issues](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294) (required ≤ 0)  
  
[See analysis details on SonarCloud](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294)

##   
![idea](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/light_bulb-16px.png 'idea') Catch issues before they fail your Quality Gate with our IDE extension ![SonarLint](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/sonarlint-16px.png 'SonarLint') [SonarLint](https://www.sonarsource.com/products/sonarlint/features/connected-mode/?referrer=pull-request)


sonarcloud[bot]: ## [![Quality Gate Failed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-failed-20px.png 'Quality Gate Failed')](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294) **Quality Gate failed**  
Failed conditions  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/failed-16px.png '') [6 New Major Issues](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294) (required ≤ 0)  
  
[See analysis details on SonarCloud](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294)

##   
![idea](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/light_bulb-16px.png 'idea') Catch issues before they fail your Quality Gate with our IDE extension ![SonarLint](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/sonarlint-16px.png 'SonarLint') [SonarLint](https://www.sonarsource.com/products/sonarlint/features/connected-mode/?referrer=pull-request)


github-actions[bot]: 
<!--
  0 failure: 
  1 warning:  This PR modified ...
  
  
  DangerID: danger-id-Danger;
-->


<table>
  <thead>
    <tr>
      <th width="50"></th>
      <th width="100%" data-danger-table="true">Warnings</th>
    </tr>
  </thead>
  <tbody><tr>
      <td>:warning:</td>
      <td>

  This PR modified some Jest snapshot file/s:
 - packages/printer-legacy/tests/unit/__snapshots__/printer.test.ts.snap
  </td>
    </tr>
  </tbody>
</table>



<p align="right">
  Generated by :no_entry_sign: <a href="https://danger.systems/js">dangerJS</a> against dc09ec9cf0c29ee57f19b7d1cbc600be54f725b4
</p>

codesee-maps[bot]: <details open>
<summary><b>👇 <a href="https://app.codesee.io/r/reviews?pr=1294&src=https%3A%2F%2Fgithub.com%2Fgraphql-markdown%2Fgraphql-markdown">Click on the image</a> for a new way to code review</b>
</summary>

####

[![Review these changes using an interactive CodeSee Map](https://s3.us-east-2.amazonaws.com/maps.codesee.io/images/github/graphql-markdown/graphql-markdown/1294/2500da01/dc09ec9cf0c29ee57f19b7d1cbc600be54f725b4.svg)](https://app.codesee.io/r/reviews?pr=1294&src=https%3A%2F%2Fgithub.com%2Fgraphql-markdown%2Fgraphql-markdown)

#### Legend
<img src="https://app.codesee.io/Legend_v3.png" alt="CodeSee Map legend" width="220" height="156">
</details>
sonarcloud[bot]: ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294) **Quality Gate passed**  
Issues  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=graphql-markdown_graphql-markdown&pullRequest=1294&resolved=false&inNewCodePeriod=true)

Measures  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=graphql-markdown_graphql-markdown&pullRequest=1294&resolved=false&inNewCodePeriod=true)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/no-data-16px.png '') No data about Coverage  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [16.5% Duplication on New Code](https://sonarcloud.io/component_measures?id=graphql-markdown_graphql-markdown&pullRequest=1294&metric=new_duplicated_lines_density&view=list)  
  
[See analysis details on SonarCloud](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294)


sonarcloud[bot]: ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294) **Quality Gate passed**  
Issues  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=graphql-markdown_graphql-markdown&pullRequest=1294&resolved=false&inNewCodePeriod=true)

Measures  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=graphql-markdown_graphql-markdown&pullRequest=1294&resolved=false&inNewCodePeriod=true)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/no-data-16px.png '') No data about Coverage  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [15.9% Duplication on New Code](https://sonarcloud.io/component_measures?id=graphql-markdown_graphql-markdown&pullRequest=1294&metric=new_duplicated_lines_density&view=list)  
  
[See analysis details on SonarCloud](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294)


sonarcloud[bot]: ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294) **Quality Gate passed**  
Issues  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=graphql-markdown_graphql-markdown&pullRequest=1294&resolved=false&inNewCodePeriod=true)

Measures  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=graphql-markdown_graphql-markdown&pullRequest=1294&resolved=false&inNewCodePeriod=true)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/no-data-16px.png '') No data about Coverage  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [15.9% Duplication on New Code](https://sonarcloud.io/component_measures?id=graphql-markdown_graphql-markdown&pullRequest=1294&metric=new_duplicated_lines_density&view=list)  
  
[See analysis details on SonarCloud](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294)


coveralls: 
[![Coverage Status](https://coveralls.io/builds/65728165/badge)](https://coveralls.io/builds/65728165)

coverage: 94.405% (-0.04%) from 94.447%
when pulling **06ec8ddc051e7ad9164248f5e2e1328cb3bf6d61 on feat/1292-support-examples**
into **054f0b5458cba9e9a663c6e11dc870fd34e00108 on main**.

sonarcloud[bot]: ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294) **Quality Gate passed**  
Issues  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=graphql-markdown_graphql-markdown&pullRequest=1294&resolved=false&inNewCodePeriod=true)

Measures  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=graphql-markdown_graphql-markdown&pullRequest=1294&resolved=false&inNewCodePeriod=true)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/no-data-16px.png '') No data about Coverage  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [15.9% Duplication on New Code](https://sonarcloud.io/component_measures?id=graphql-markdown_graphql-markdown&pullRequest=1294&metric=new_duplicated_lines_density&view=list)  
  
[See analysis details on SonarCloud](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294)


sonarcloud[bot]: ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294) **Quality Gate passed**  
Issues  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=graphql-markdown_graphql-markdown&pullRequest=1294&resolved=false&inNewCodePeriod=true)

Measures  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=graphql-markdown_graphql-markdown&pullRequest=1294&resolved=false&inNewCodePeriod=true)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/no-data-16px.png '') No data about Coverage  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [15.2% Duplication on New Code](https://sonarcloud.io/component_measures?id=graphql-markdown_graphql-markdown&pullRequest=1294&metric=new_duplicated_lines_density&view=list)  
  
[See analysis details on SonarCloud](https://sonarcloud.io/dashboard?id=graphql-markdown_graphql-markdown&pullRequest=1294)



Patch:
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 234f8bac..536a6a24 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -18,10 +18,12 @@
     "coverallsapp",
     "dangerfile",
     "davidyaha",
+    "dbaeumer",
     "dockerhub",
     "Earthfile",
     "earthlyignore",
     "edno",
+    "esbenp",
     "foobaz",
     "frontmatter",
     "GraphQLID",
@@ -38,6 +40,7 @@
     "jocrau",
     "Jost",
     "knip",
+    "knisterpeter",
     "lauzierj",
     "lcov",
     "ljiang-ti",
diff --git a/docs/advanced/examples.md b/docs/advanced/examples.md
new file mode 100644
index 00000000..e85d9e59
--- /dev/null
+++ b/docs/advanced/examples.md
@@ -0,0 +1,6 @@
+---
+pagination_prev: null
+pagination_next: null
+---
+
+# Examples
diff --git a/docs/settings.md b/docs/settings.md
index 9c98d1d3..34caf4d3 100644
--- a/docs/settings.md
+++ b/docs/settings.md
@@ -228,6 +228,7 @@ Use these options to toggle type information rendered on pages:
   - `default`: deprecated entities are displayed with other entities.
   - `group`: deprecated entities are grouped together.
   - `skip`: deprecated entities are not displayed (same as [`skipDocDirective`](#skipdocdirective)).
+- `exampleSection`: display example section based on directive data (see [Examples](/docs/advanced/examples)).
 - `parentTypePrefix`: prefix field names with parent type name.
 - `relatedTypeSection`: display related type sections.
 - `typeBadges`: add field type attributes badges.
@@ -237,6 +238,7 @@ Use these options to toggle type information rendered on pages:
 | ------------------------------------- | ----------------------- | --------- |
 | `printTypeOptions.codeSection`        | `--noCode`              | `true`    |
 | `printTypeOptions.deprecated`         | `--deprecated <option>` | `default` |
+| `printTypeOptions.exampleSection`     | `--noExample`           | `true`    |
 | `printTypeOptions.parentTypePrefix`   | `--noParentType`        | `true`    |
 | `printTypeOptions.relatedTypeSection` | `--noRelatedType`       | `true`    |
 | `printTypeOptions.typeBadges`         | `--noTypeBadges`        | `true`    |
@@ -257,6 +259,7 @@ plugins: [
         printTypeOptions: {
           codeSection: false, // disable code section, same as CLI flag --noCode
           deprecated: "group", // group deprecated entities, same as CLI flag --deprecated group
+          exampleSection: false, // disable code section, same as CLI flag --noExample
           parentTypePrefix: false, // disable parent prefix, same as CLI flag --noParentType
           relatedTypeSection: false, // disable related type sections, same as CLI flag --noRelatedType
           typeBadges: false, // disable type attribute badges, same as CLI flag --noTypeBadges
diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts
index 0becdd4b..c624c429 100644
--- a/packages/core/src/config.ts
+++ b/packages/core/src/config.ts
@@ -72,6 +72,7 @@ export const DEFAULT_OPTIONS: Required<
   printTypeOptions: {
     codeSection: true,
     deprecated: DeprecatedOption.DEFAULT,
+    exampleSection: true,
     parentTypePrefix: true,
     relatedTypeSection: true,
     typeBadges: true,
@@ -281,6 +282,9 @@ export const getPrintTypeOptions = (
         configOptions?.deprecated ??
         DEFAULT_OPTIONS.printTypeOptions.deprecated!) as string
     ).toLocaleLowerCase() as TypeDeprecatedOption,
+    exampleSection:
+      (!cliOpts?.noExample && configOptions?.exampleSection) ??
+      DEFAULT_OPTIONS.printTypeOptions.exampleSection!,
     parentTypePrefix:
       (!cliOpts?.noParentType && configOptions?.parentTypePrefix) ??
       DEFAULT_OPTIONS.printTypeOptions.parentTypePrefix!,
diff --git a/packages/docusaurus/src/index.ts b/packages/docusaurus/src/index.ts
index a025305d..0b19546d 100644
--- a/packages/docusaurus/src/index.ts
+++ b/packages/docusaurus/src/index.ts
@@ -55,6 +55,7 @@ export default function pluginGraphQLDocGenerator(
         )
         .option("--noApiGroup", "Disable API grouping for types")
         .option("--noCode", "Disable code section for types")
+        .option("--noExample", "Disable example section for types")
         .option("--noParentType", "Disable parent type name as field prefix")
         .option("--noRelatedType", "Disable related types sections")
         .option("--noTypeBadges", "Disable badges for types")
diff --git a/packages/graphql/src/introspection.ts b/packages/graphql/src/introspection.ts
index c5e77c2e..60dcccf9 100644
--- a/packages/graphql/src/introspection.ts
+++ b/packages/graphql/src/introspection.ts
@@ -40,6 +40,8 @@ import { instanceOf } from "./guard";
 
 export { getNamedType, printSchema } from "graphql";
 
+export class IntrospectionError extends Error {}
+
 /**
  * Returns a map of GraphQL named types from a schema for a defined GraphQL type.
  * When parsing the entities, internal GraphQL entities (starting with `__`) are excluded.
@@ -110,7 +112,7 @@ export const getDirectiveLocationForASTPath = (
   appliedTo: Maybe<ASTNode>,
 ): DirectiveLocation => {
   if (!appliedTo || !("kind" in appliedTo)) {
-    throw new Error("Unexpected kind: " + String(appliedTo));
+    throw new IntrospectionError("Unexpected kind: " + String(appliedTo));
   }
 
   switch (appliedTo.kind) {
@@ -146,7 +148,9 @@ export const getDirectiveLocationForASTPath = (
       return DirectiveLocation.ARGUMENT_DEFINITION;
     // Not reachable, all possible types have been considered.
     default:
-      throw new Error("Unexpected kind: " + String(appliedTo.kind));
+      throw new IntrospectionError(
+        "Unexpected kind: " + String(appliedTo.kind),
+      );
   }
 };
 
@@ -284,14 +288,14 @@ export const getTypeDirectiveArgValue = (
   directive: GraphQLDirective,
   node: unknown,
   argName: string,
-): Maybe<Record<string, unknown>> => {
+): Maybe<Record<string, unknown> | string> => {
   const args = getTypeDirectiveValues(directive, node);
 
   if (!args?.[argName]) {
-    throw new Error(`Directive argument '${argName}' not found!`);
+    throw new IntrospectionError(`Directive argument '${argName}' not found!`);
   }
 
-  return args[argName] as Maybe<Record<string, unknown>>;
+  return args[argName] as Maybe<Record<string, unknown> | string>;
 };
 
 /**
diff --git a/packages/printer-legacy/src/const/options.ts b/packages/printer-legacy/src/const/options.ts
index 54b66dcd..d3e9bdcc 100644
--- a/packages/printer-legacy/src/const/options.ts
+++ b/packages/printer-legacy/src/const/options.ts
@@ -21,6 +21,7 @@ export const PRINT_TYPE_DEFAULT_OPTIONS: Required<PrinterConfigPrintTypeOptions>
   {
     codeSection: true,
     deprecated: "default",
+    exampleSection: true,
     metatags: [],
     parentTypePrefix: true,
     relatedTypeSection: true,
diff --git a/packages/printer-legacy/src/example.ts b/packages/printer-legacy/src/example.ts
new file mode 100644
index 00000000..64099a75
--- /dev/null
+++ b/packages/printer-legacy/src/example.ts
@@ -0,0 +1,50 @@
+import type { Maybe, GraphQLDirective } from "@graphql-markdown/types";
+
+import {
+  IntrospectionError,
+  getFields,
+  getTypeDirectiveArgValue,
+  hasDirective,
+} from "@graphql-markdown/graphql";
+
+export const printExample = (
+  type: unknown,
+  directiveExample: {
+    directive: GraphQLDirective;
+    argName: string;
+  },
+): Maybe<string> => {
+  try {
+    const arg = getTypeDirectiveArgValue(
+      directiveExample.directive,
+      type,
+      directiveExample.argName,
+    );
+
+    return arg ? String(arg) : undefined;
+  } catch (err: unknown) {
+    if (err instanceof IntrospectionError) {
+      const fields = getFields(type) as {
+        astNode: unknown;
+        name: string;
+        type: unknown;
+      }[];
+      if (fields.length === 0) {
+        return undefined;
+      }
+
+      let example = {};
+      fields.forEach((field) => {
+        const fieldType = hasDirective(field, [directiveExample.directive])
+          ? field
+          : field.type;
+        example = {
+          ...example,
+          [field.name]: printExample(fieldType, directiveExample),
+        };
+      });
+      return JSON.stringify(example);
+    }
+    throw err;
+  }
+};
diff --git a/packages/printer-legacy/src/printer.ts b/packages/printer-legacy/src/printer.ts
index 30d8bd73..52580219 100644
--- a/packages/printer-legacy/src/printer.ts
+++ b/packages/printer-legacy/src/printer.ts
@@ -62,7 +62,12 @@ import {
   MARKDOWN_SOC,
 } from "./const/strings";
 import { mdx } from "./const/mdx";
-import { DEFAULT_OPTIONS, PRINT_TYPE_DEFAULT_OPTIONS } from "./const/options";
+import {
+  DEFAULT_OPTIONS,
+  PRINT_TYPE_DEFAULT_OPTIONS,
+  SectionLevels,
+} from "./const/options";
+import { printExample } from "./example";
 
 export class Printer implements IPrinter {
   static options: Readonly<Maybe<PrintTypeOptions>>;
@@ -111,6 +116,9 @@ export class Printer implements IPrinter {
       codeSection:
         printTypeOptions?.codeSection ?? PRINT_TYPE_DEFAULT_OPTIONS.codeSection,
       customDirectives,
+      exampleSection:
+        printTypeOptions?.exampleSection ??
+        PRINT_TYPE_DEFAULT_OPTIONS.exampleSection,
       groups,
       parentTypePrefix:
         printTypeOptions?.parentTypePrefix ??
@@ -186,6 +194,47 @@ export class Printer implements IPrinter {
     return MARKDOWN_SOC + code.trim() + MARKDOWN_EOC;
   };
 
+  static readonly printExample = (
+    type: unknown,
+    options: PrintTypeOptions,
+  ): string => {
+    if (
+      typeof options.exampleSection === "undefined" ||
+      options.exampleSection === null ||
+      options.exampleSection === false
+    ) {
+      return "";
+    }
+
+    let directiveName: string = "example",
+      argName: string = "value";
+    if (typeof options.exampleSection === "object") {
+      if (
+        "directive" in options.exampleSection &&
+        options.exampleSection.directive
+      ) {
+        directiveName = options.exampleSection.directive;
+      }
+      if ("arg" in options.exampleSection && options.exampleSection.arg) {
+        argName = options.exampleSection.arg;
+      }
+    }
+
+    const directive = options.schema?.getDirective(directiveName);
+
+    if (!directive) {
+      return "";
+    }
+
+    const example = printExample(type, { directive, argName });
+
+    if (!example) {
+      return "";
+    }
+
+    return `${SectionLevels.LEVEL_3} Example${MARKDOWN_EOP}${MARKDOWN_SOC}${example}${MARKDOWN_EOC}${MARKDOWN_EOP}`;
+  };
+
   static readonly printTypeMetadata = (
     type: unknown,
     options: PrintTypeOptions,
@@ -274,6 +323,7 @@ export class Printer implements IPrinter {
     const tags = Printer.printCustomTags(type, printTypeOptions);
     const metadata = Printer.printTypeMetadata(type, printTypeOptions);
     const relations = Printer.printRelations(type, printTypeOptions);
+    const example = Printer.printExample(type, printTypeOptions);
 
     return [
       header,
@@ -284,6 +334,7 @@ export class Printer implements IPrinter {
       code,
       customDirectives,
       metadata,
+      example,
       relations,
     ].join(MARKDOWN_EOP) as MDXString;
   };
diff --git a/packages/types/src/core.d.ts b/packages/types/src/core.d.ts
index fef8334c..1ed68f7c 100644
--- a/packages/types/src/core.d.ts
+++ b/packages/types/src/core.d.ts
@@ -25,6 +25,7 @@ export type TypeDeprecatedOption = "default" | "group" | "skip";
 export interface ConfigPrintTypeOptions {
   codeSection?: boolean;
   deprecated?: TypeDeprecatedOption;
+  exampleSection?: boolean;
   parentTypePrefix?: boolean;
   relatedTypeSection?: boolean;
   typeBadges?: boolean;
@@ -73,6 +74,7 @@ export interface CliOptions {
   link?: string;
   noApiGroup?: boolean;
   noCode?: boolean;
+  noExample?: boolean;
   noParentType?: boolean;
   noRelatedType?: boolean;
   noTypeBadges?: boolean;
diff --git a/packages/types/src/printer.d.ts b/packages/types/src/printer.d.ts
index 2b4119f6..baf148ce 100644
--- a/packages/types/src/printer.d.ts
+++ b/packages/types/src/printer.d.ts
@@ -28,6 +28,7 @@ export type RootTypeLocale = {
 
 export interface PrinterConfigPrintTypeOptions {
   codeSection?: boolean;
+  exampleSection?: ExampleDirectiveOption | boolean;
   deprecated?: TypeDeprecatedOption;
   metatags?: Record<string, string>[];
   parentTypePrefix?: boolean;
@@ -41,12 +42,18 @@ export interface CollapsibleOption {
   dataClose: string;
 }
 
+export interface ExampleDirectiveOption {
+  directive?: string;
+  arg?: string;
+}
+
 export interface PrintTypeOptions {
   basePath: string;
   codeSection?: Maybe<boolean>;
   collapsible?: Maybe<CollapsibleOption>;
   customDirectives?: Maybe<CustomDirectiveMap>;
   deprecated?: Maybe<TypeDeprecatedOption>;
+  exampleSection?: Maybe<ExampleDirectiveOption | boolean>;
   frontMatter?: Maybe<FrontMatterOptions>;
   groups?: Maybe<SchemaEntitiesGroupMap>;
   level?: Maybe<SectionLevelValue>;


Test patch:
diff --git a/packages/core/tests/unit/config.test.ts b/packages/core/tests/unit/config.test.ts
index c54bb49e..51a297ef 100644
--- a/packages/core/tests/unit/config.test.ts
+++ b/packages/core/tests/unit/config.test.ts
@@ -232,6 +232,7 @@ describe("config", () => {
         printTypeOptions: {
           codeSection: false,
           deprecated: "group",
+          exampleSection: false,
           parentTypePrefix: false,
           relatedTypeSection: false,
           typeBadges: false,
diff --git a/packages/core/tests/unit/graphql-config.test.ts b/packages/core/tests/unit/graphql-config.test.ts
index 4ea406ff..48c34415 100644
--- a/packages/core/tests/unit/graphql-config.test.ts
+++ b/packages/core/tests/unit/graphql-config.test.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unsafe-return */
 /* eslint-disable @typescript-eslint/no-explicit-any */
 import { vol } from "memfs";
 
diff --git a/packages/docusaurus/tests/__data__/schema_with_grouping.graphql b/packages/docusaurus/tests/__data__/schema_with_grouping.graphql
index 82363ffd..3b1b6ca8 100644
--- a/packages/docusaurus/tests/__data__/schema_with_grouping.graphql
+++ b/packages/docusaurus/tests/__data__/schema_with_grouping.graphql
@@ -1,9 +1,18 @@
+"""
+Example of example directive for `exampleSection`.
+
+See [documentation](https://graphql-markdown.github.io/docs/settings#printtypeoptions)
+"""
+directive @example(
+  value: String
+) on OBJECT | INPUT_OBJECT | UNION | ENUM | INTERFACE | FIELD_DEFINITION | ARGUMENT_DEFINITION | QUERY | MUTATION | SCALAR
+
 """
 Example of custom directive for `skipDocDirective`.
 
 See [documentation](https://graphql-markdown.github.io/docs/settings#skipdocdirective)
 """
-directive @noDoc on OBJECT | INTERFACE | FIELD_DEFINITION
+directive @noDoc on OBJECT | INTERFACE | FIELD_DEFINITION | SCALAR
 
 """
 Example of custom directive for `groupByDirective`.
@@ -17,7 +26,7 @@ directive @doc(
   See [documentation](https://graphql-markdown.github.io/docs/settings#groupbydirective)
   """
   category: String
-) on OBJECT | INPUT_OBJECT | UNION | ENUM | INTERFACE | FIELD_DEFINITION | ARGUMENT_DEFINITION
+) on OBJECT | INPUT_OBJECT | UNION | ENUM | INTERFACE | FIELD_DEFINITION | ARGUMENT_DEFINITION | SCALAR
 
 """
 Example of custom directive for `customDirective`.
@@ -30,13 +39,13 @@ directive @complexity(
 
   If the field needs to call an expensive service to resolve itself, then the complexity should be at a high level but if the field is easy to resolve and not an expensive operation, the complexity should be at a low level.
   """
-  value: Int!
+  value: Int! @example(value: "1")
   """
   An array containing names of parameters present in the GraphQL field.
 
   Use parameters values to compute the field's cost dynamically. If the parameter is an array, its multiplier value will be the length of the array.
   """
-  multipliers: [String!]
+  multipliers: [String!] @example(value: "[\\\"roles\\\"]")
 ) on FIELD_DEFINITION
 
 """
@@ -58,11 +67,11 @@ See [documentation](https://graphql-markdown.github.io/docs/settings#skipdocdire
 """
 directive @beta on OBJECT | INTERFACE | FIELD_DEFINITION
 
-scalar Date
-scalar EmailAddress
-scalar PhoneNumber
-scalar Time
-scalar URL @specifiedBy(url: "https://tools.ietf.org/html/rfc3986")
+scalar Date @example(value: "1970-01-01")
+scalar EmailAddress @example(value: "john.doe@corp.com")
+scalar PhoneNumber @example(value: "1-234-4567")
+scalar Time @example(value: "01:02:23.453")
+scalar URL @specifiedBy(url: "https://tools.ietf.org/html/rfc3986") @example(value: "https://tools.ietf.org/html/rfc3986")
 
 type Mutation {
   UpdateGrade(input: String): String @doc(category: "Grade") @auth
@@ -107,15 +116,15 @@ type Query {
 }
 
 type UnusedType implements Record @noDoc {
-  id: ID!
+  id: ID! @example(value: "1")
 }
 
 interface Record {
-  id: ID!
+  id: ID! @example(value: "1")
 }
 
 type Semester implements Record {
-  id: ID!
+  id: ID! @example(value: "1")
   startDate: Date
   withdrawDate: Date @deprecated
   endDate: Date
@@ -126,17 +135,17 @@ type Semester implements Record {
 }
 
 type DepartmentInformation implements Record @auth {
-  id: ID!
-  uuid: String @beta
+  id: ID! @example(value: "1")
+  uuid: String @beta @example(value: "9c5b94b1-35ad-49bb-b118-8e8fc24abf80")
   email: EmailAddress
   number: PhoneNumber
   departmentOpenTime: Time
   departmentCloseTime: Time
   website: URL
-  employees(skip: Int): [String!]!
+  employees(skip: Int): [String!]! @example(value: "[\\\"John Doe\\\"]")
 }
 
 type Course {
-  id: ID!
-  title: String!
+  id: ID! @example(value: "1")
+  title: String! @example(value: "GraphQL")
 }
diff --git a/packages/graphql/tests/unit/introspection.test.ts b/packages/graphql/tests/unit/introspection.test.ts
index 2a683d38..38e489f3 100644
--- a/packages/graphql/tests/unit/introspection.test.ts
+++ b/packages/graphql/tests/unit/introspection.test.ts
@@ -10,7 +10,9 @@ jest.mock("graphql", () => {
     getDirectiveValues: jest.fn(graphql.getDirectiveValues),
   };
 });
+
 import type { GraphQLSchema, ObjectTypeDefinitionNode, ASTNode } from "graphql";
+
 import {
   buildSchema,
   DirectiveLocation,
@@ -38,6 +40,7 @@ import {
   hasDirective,
   isValidDirectiveLocation,
   getDirectiveLocationForASTPath,
+  IntrospectionError,
 } from "../../src/introspection";
 import { loadSchema } from "../../src/loader";
 
@@ -501,7 +504,7 @@ describe("introspection", () => {
     `);
     const type = schema.getType("Test")!;
 
-    test("throws an error if argument does not exist", () => {
+    test("throws IntrospectionError if argument does not exist", () => {
       expect.assertions(1);
 
       const directiveName = "dirWithoutArg";
@@ -510,7 +513,9 @@ describe("introspection", () => {
 
       expect(() => {
         getTypeDirectiveArgValue(directiveType, type.astNode!, argName);
-      }).toThrow(`Directive argument '${argName}' not found!`);
+      }).toThrow(
+        new IntrospectionError(`Directive argument '${argName}' not found!`),
+      );
     });
 
     test("returns fields value if argument is of input type", () => {
diff --git a/packages/printer-legacy/tests/unit/__snapshots__/printer.test.ts.snap b/packages/printer-legacy/tests/unit/__snapshots__/printer.test.ts.snap
index 81e22c20..11340c1c 100644
--- a/packages/printer-legacy/tests/unit/__snapshots__/printer.test.ts.snap
+++ b/packages/printer-legacy/tests/unit/__snapshots__/printer.test.ts.snap
@@ -71,3 +71,27 @@ Union
 \`\`\`
 "
 `;
+
+exports[`Printer printExample() returns a Markdown graphql codeblock with example 1`] = `
+"### Example
+
+
+\`\`\`graphql
+This is an example
+\`\`\`
+
+
+"
+`;
+
+exports[`Printer printExample() returns a Markdown graphql codeblock with example options override 1`] = `
+"### Example
+
+
+\`\`\`graphql
+This is an example
+\`\`\`
+
+
+"
+`;
diff --git a/packages/printer-legacy/tests/unit/example.test.ts b/packages/printer-legacy/tests/unit/example.test.ts
new file mode 100644
index 00000000..e21c1111
--- /dev/null
+++ b/packages/printer-legacy/tests/unit/example.test.ts
@@ -0,0 +1,76 @@
+import { buildSchema } from "graphql";
+
+import { printExample } from "../../src/example";
+
+describe("example", () => {
+  const schema = buildSchema(`
+  directive @example(
+    value: String
+  ) on OBJECT | FIELD_DEFINITION | SCALAR
+
+  scalar ScalarExample @example(value: "This is an example")
+
+  scalar JSON
+
+  type TypeExtrapolateExample {
+    example: ScalarExample
+    value: JSON @example(value: "{\\"example\\": \\"This is an example\\"}")
+    id: ID!
+  }
+
+  type TypeExample @example(value: "{\\"example\\": \\"This is an example\\", \\"value\\": {}}") {
+    example: ScalarExample
+    value: JSON
+    id: ID!
+  }
+`);
+  const exampleDirective = schema.getDirective("example")!;
+
+  describe("printExample()", () => {
+    test("returns a formatted example for the type using @example directive for scalar", () => {
+      expect.assertions(1);
+
+      expect(
+        printExample(schema.getType("ScalarExample"), {
+          directive: exampleDirective,
+          argName: "value",
+        }),
+      ).toBe("This is an example");
+    });
+
+    test("returns undefined if no example directive", () => {
+      expect.assertions(1);
+
+      expect(
+        printExample(schema.getType("JSON"), {
+          directive: exampleDirective,
+          argName: "value",
+        }),
+      ).toBeUndefined();
+    });
+
+    test("returns JSON formatted string example using subtype examples", () => {
+      expect.assertions(1);
+
+      expect(
+        printExample(schema.getType("TypeExtrapolateExample"), {
+          directive: exampleDirective,
+          argName: "value",
+        }),
+      ).toBe(
+        '{"example":"This is an example","value":"{\\"example\\": \\"This is an example\\"}"}',
+      );
+    });
+
+    test("returns a formatted example for the type using @example directive for complex type", () => {
+      expect.assertions(1);
+
+      expect(
+        printExample(schema.getType("TypeExample"), {
+          directive: exampleDirective,
+          argName: "value",
+        }),
+      ).toBe('{"example": "This is an example", "value": {}}');
+    });
+  });
+});
diff --git a/packages/printer-legacy/tests/unit/printer.test.ts b/packages/printer-legacy/tests/unit/printer.test.ts
index 60e9648b..f48b8d8f 100644
--- a/packages/printer-legacy/tests/unit/printer.test.ts
+++ b/packages/printer-legacy/tests/unit/printer.test.ts
@@ -10,6 +10,7 @@ import {
   GraphQLScalarType,
   GraphQLUnionType,
   GraphQLSchema,
+  GraphQLString,
 } from "graphql";
 
 import type { PrintTypeOptions } from "@graphql-markdown/types";
@@ -43,6 +44,9 @@ import * as GraphQL from "@graphql-markdown/graphql";
 jest.mock("../../src/graphql");
 import * as GraphQLPrinter from "../../src/graphql";
 
+jest.mock("../../src/example");
+import * as ExamplePrinter from "../../src/example";
+
 import * as Common from "../../src/common";
 
 import { Printer } from "../../src/printer";
@@ -170,6 +174,7 @@ describe("Printer", () => {
           "collapsible": undefined,
           "customDirectives": undefined,
           "deprecated": "default",
+          "exampleSection": true,
           "frontMatter": {},
           "groups": undefined,
           "level": undefined,
@@ -211,6 +216,7 @@ describe("Printer", () => {
         groups: {},
         printTypeOptions: {
           codeSection: false,
+          exampleSection: false,
           parentTypePrefix: false,
           relatedTypeSection: false,
           typeBadges: false,
@@ -226,6 +232,7 @@ describe("Printer", () => {
           "collapsible": undefined,
           "customDirectives": undefined,
           "deprecated": "default",
+          "exampleSection": false,
           "frontMatter": {},
           "groups": {},
           "level": undefined,
@@ -463,4 +470,102 @@ describe("Printer", () => {
 </head>`);
     });
   });
+
+  describe("printExample()", () => {
+    test("returns a Markdown graphql codeblock with example", () => {
+      expect.hasAssertions();
+
+      const spy = jest
+        .spyOn(ExamplePrinter, "printExample")
+        .mockReturnValue("This is an example");
+
+      const code = Printer.printExample(GraphQLString, {
+        ...DEFAULT_OPTIONS,
+        schema: {
+          getDirective: (name: string) => {
+            return { name } as GraphQLDirective;
+          },
+        } as GraphQLSchema,
+      });
+
+      expect(spy).toHaveBeenCalledWith(GraphQLString, {
+        argName: "value",
+        directive: { name: "example" },
+      });
+      expect(code).toMatchSnapshot();
+    });
+
+    test("returns an empty string if printTypeOptions.exampleSection is false", () => {
+      expect.hasAssertions();
+
+      const spy = jest
+        .spyOn(ExamplePrinter, "printExample")
+        .mockReturnValue("This is an example");
+
+      const code = Printer.printExample(GraphQLString, {
+        ...DEFAULT_OPTIONS,
+        exampleSection: false,
+      });
+
+      expect(spy).not.toHaveBeenCalled();
+      expect(code).toBe("");
+    });
+
+    test("returns an empty string if printExample returns undefined", () => {
+      expect.hasAssertions();
+
+      jest.spyOn(ExamplePrinter, "printExample").mockReturnValue(undefined);
+
+      const code = Printer.printExample(GraphQLString, DEFAULT_OPTIONS);
+
+      expect(code).toBe("");
+    });
+
+    test("returns a Markdown graphql codeblock with example options override", () => {
+      expect.hasAssertions();
+
+      const spy = jest
+        .spyOn(ExamplePrinter, "printExample")
+        .mockReturnValue("This is an example");
+
+      const code = Printer.printExample(GraphQLString, {
+        ...DEFAULT_OPTIONS,
+        exampleSection: {
+          directive: "set",
+          arg: "examples",
+        },
+        schema: {
+          getDirective: (name: string) => {
+            return { name } as GraphQLDirective;
+          },
+        } as GraphQLSchema,
+      });
+
+      expect(spy).toHaveBeenCalledWith(GraphQLString, {
+        argName: "examples",
+        directive: { name: "set" },
+      });
+      expect(code).toMatchSnapshot();
+    });
+
+    test("returns an empty string if printTypeOptions.exampleSection directive is invalid", () => {
+      expect.hasAssertions();
+
+      const spy = jest
+        .spyOn(ExamplePrinter, "printExample")
+        .mockReturnValue("This is an example");
+
+      const code = Printer.printExample(GraphQLString, {
+        ...DEFAULT_OPTIONS,
+        schema: {
+          getDirective: () => {
+            return undefined;
+          },
+        } as unknown as GraphQLSchema,
+      });
+
+      expect(spy).not.toHaveBeenCalled();
+      expect(code).toBe("");
+    });
+  });
 });