Skip to Content
Vuesho

GraphQL

Reference pages from GraphQL schemas.

@vuesho/graphql generates reference pages for the operations and types of GraphQL schemas, with code samples and a playground that runs queries, mutations and subscriptions. The example documents a store's schema, with a mock endpoint.

Setup

Install the Packages

npm i @vuesho/graphql graphql

Add the Source and Plugin

createGraphQL() loads the schemas, staticSource() returns their pages as a content source under baseDir, and graphqlPlugin() renders the pages:

vuesho.config.ts
import { createGraphQL, graphqlPlugin } from "@vuesho/graphql";
import { createSite, recommendedPreset } from "vuesho/config";
import { defineDocs } from "vuesho/content";

const docs = defineDocs();
// An SDL file from the project root, or a URL.
const graphql = createGraphQL({ input: ["schema.graphql"] });

export default createSite({
  docs: docs.toSource(),
  api: graphql.staticSource({ baseDir: "api" }), 
}).plugins(recommendedPreset(), graphqlPlugin());

Run vuesho dev and open a page under /api, like /api/queries/customer for the query customer.

Connect the Playground

The playground needs your GraphQL endpoint's URL. Pass it to createGraphQL():

vuesho.config.ts
const graphql = createGraphQL({
  input: ["schema.graphql"],
  playground: { url: "https://api.example.com/graphql" }, 
});

A URL that is a path of the site, like /api/graphql, gets the base path.

Name the Folder

The pages are in an api folder in the sidebar. To give the folder a title, add a meta file to the content folder:

content/api/meta.json
{ "title": "GraphQL API" }

Pages

Each operation has a page in its kind's folder, like queries, with the kind as a badge in the sidebar. The generated pages are in search and llms.txt, like your other pages. includeTypes adds a page for each named type, and per: "file" puts each schema on one page, as the tabs show for the example:

customer.md
orders.md
search.md
node.md
createOrder.md
legacyCreateOrder.md
orderUpdated.md

An operation's page shows the types it uses, with or without includeTypes. To generate pages for only some operations or types, pass a function to includeOperations or includeTypes:

vuesho.config.ts
graphql.staticSource({
  baseDir: "api",
  includeOperations: (kind) => kind !== "subscription",
  includeTypes: (type) => !type.name.startsWith("Internal"),
  // Generates the folders' meta files.
  meta: true,
});

groupBy: "none" leaves out the kind folders. badges: false on graphqlPlugin() removes the kind badges and the strikethrough on deprecated operations from the sidebar.

Examples

Each operation has an example generated from its arguments. examples replaces the generated examples with named operations from GraphQL files, URLs or text. A list applies to every schema, and a record maps each schema ID to its files:

vuesho.config.ts
const graphql = createGraphQL({
  input: { store: "graphql/store.graphql" },
  examples: ["graphql/examples.graphql"], 
});

An example shows on the page of each root field it selects, titled by its name, like "Customer Profile". The comment above it is its description, in Markdown, and the default values of its variables fill the playground:

graphql/examples.graphql
# Public profile of a customer.
query CustomerProfile($id: ID! = "cus_42") {
  customer(id: $id) {
    id
    name
  }
}

Pass each argument as a variable of the same name, like id: $id, since the playground edits arguments as variables.

Schemas

Multiple Schemas

A schema's ID is its file name, or the last segment of its URL, without the extension. To choose the IDs, pass a record:

vuesho.config.ts
const graphql = createGraphQL({
  input: {
    // An SDL file's path or URL, or SDL text, an introspection result or a `GraphQLSchema`
    store: "graphql/store.graphql",
    // SDL files, merged with their type extensions
    admin: ["graphql/base.graphql", "graphql/admin.graphql"],
    // A function that returns one of these
    galaxy: async () => {
      const response = await fetch("https://example.com/introspection.json");
      return response.json();
    },
  },
});

To put each schema in a separate folder, prefix the file name with this.id in name:

vuesho.config.ts
graphql.staticSource({
  baseDir: "api",
  per: "item",
  groupBy: "none",
  name(output) {
    return `${this.id}/${output.item.name}`; 
  },
});

input as a Function

input can be a function, called once with onRead. Call onRead with each local file it reads, like a config that lists the schemas, so the built server gets those files too:

vuesho.config.ts
import { readFileSync } from "node:fs";

const graphql = createGraphQL({
  input(onRead) {
    onRead("api-config.json");
    const config: { schemas: string[] } = JSON.parse(readFileSync("api-config.json", "utf8"));
    return config.schemas;
  },
});

Live Updates

staticSource() reads the schemas when the site starts, so restart vuesho dev after you edit one.

dynamicSource() reads the schemas on the server, renders the pages on request, and reads the schemas again after staleTime, like any dynamic source:

vuesho.config.ts
createSite({
  docs: docs.toSource(),
  api: graphql.staticSource({ baseDir: "api" }), 
  api: graphql.dynamicSource({ baseDir: "api", staleTime: 60_000 }), 
});

Deploy a local schema with the server, since dynamicSource() reads it there.

Playground

The playground sends an operation to url with HTTP POST, with fields for its variables and headers. The browser stores the headers a reader enters, separately for each endpoint origin:

vuesho.config.ts
const graphql = createGraphQL({
  input: ["schema.graphql"],
  playground: {
    url: "https://api.example.com/graphql",
    // Shows the URL as text, which readers can't edit.
    allowUrlEdit: false,
    // The default headers, when a reader has none stored.
    headers: { "X-Client-Name": "docs" },
  },
});

No Secrets in Headers

headers reach the browser and show in the code samples, so never put a secret in them.

fetcher replaces the request that sends queries and mutations, for example to send them through a proxy. Pass it to createGraphQLPage(), and set the page component as the graphql page body in your theme:

src/graphql-page.ts
import { createGraphQLPage } from "@vuesho/graphql/ui";

export const GraphQLPage = createGraphQLPage({
  playground: {
    async fetcher(request) {
      const start = performance.now();
      const response = await fetch("/api/proxy", {
        method: "POST",
        headers: { "Content-Type": "application/json", ...request.headers },
        body: JSON.stringify({ query: request.query, variables: request.variables }),
      });

      return {
        type: "response",
        status: response.status,
        time: performance.now() - start,
        body: await response.text(),
        contentType: response.headers.get("Content-Type") ?? "",
        headers: [...response.headers],
      };
    },
  },
});
src/theme.ts
import { defineTheme } from "vuesho/theme";
import defaultTheme from "vuesho/theme/default";
import type app from "../vuesho.config";

export default defineTheme<typeof app>({
  extends: defaultTheme,
  bodies: { graphql: () => import("./graphql-page").then((mod) => mod.GraphQLPage) }, 
});

Subscriptions

A subscription connects to subscriptionUrl, which defaults to url with a ws:// or wss:// scheme. A ws(s):// URL uses the graphql-ws protocol, which sends the headers in its connection_init message. An http(s):// URL uses GraphQL over Server-Sent Events:

vuesho.config.ts
const graphql = createGraphQL({
  input: ["schema.graphql"],
  playground: {
    url: "https://api.example.com/graphql",
    subscriptionUrl: "https://api.example.com/graphql", 
  },
});

Customization

To customize the page beyond its endpoint, pass options to createGraphQLPage() and set it as the graphql page body, as Playground shows. To use <GraphQLPage> in Markdown with the same options, re-export it from src/components/content/:

src/components/content/GraphQLPage.ts
export { GraphQLPage as default } from "../../graphql-page";

On a site with several sources, give it source, the key in createSite() of the GraphQL source.

Code Samples

A query or a mutation has samples in GraphQL, cURL, JavaScript, Go, Python, Java, C# and Rust, which send it to the endpoint's url with its headers. A subscription has only the GraphQL sample. codeUsages changes the languages:

src/graphql-page.ts
import {
  createCodeUsageGeneratorRegistry,
  createGraphQLPage,
  registerDefaultCodeUsages,
} from "@vuesho/graphql/ui";

const codeUsages = registerDefaultCodeUsages(createCodeUsageGeneratorRegistry());
codeUsages.remove("java");
codeUsages.add("graphql-request", {
  label: "graphql-request",
  lang: "js",
  generate: ({ url, query, variables = {} }) =>
    `await request(${JSON.stringify(url)}, ${JSON.stringify(query)}, ${JSON.stringify(variables)});`,
});

export const GraphQLPage = createGraphQLPage({ codeUsages });

A type links to its page, and a type's page links to the operations that use it. typeLinks and operationLinks return other URLs, or undefined for no link:

src/graphql-page.ts
import { createGraphQLPage } from "@vuesho/graphql/ui";

export const GraphQLPage = createGraphQLPage({
  typeLinks: (name) => `/reference/types/${name}`,
  operationLinks: (kind, name) => `/reference/${kind}/${name}`,
});

Components

components replaces parts of the page. A layout receives the parts as named slots, so it can reorder them:

src/OperationLayout.vue
<script setup lang="ts">
import type { OperationLayoutProps } from "@vuesho/graphql/client";

defineProps<OperationLayoutProps>();
</script>

<template>
  <div class="flex flex-col gap-6">
    <slot name="header" />
    <slot name="deprecated" />
    <slot name="description" />
    <slot name="playground" />
    <slot name="arguments" />
    <slot name="returns" />
    <slot name="example" />
  </div>
</template>
src/graphql-page.ts
import { createGraphQLPage } from "@vuesho/graphql/ui";
import OperationLayout from "./OperationLayout.vue";

export const GraphQLPage = createGraphQLPage({ components: { OperationLayout } });

To change a part freely, copy it into src/ui/@vuesho/graphql/ with vuesho add:

npx vuesho add operation --from @vuesho/graphql
src/graphql-page.ts
import { createGraphQLPage } from "@vuesho/graphql/ui";
import { Operation } from "./ui/@vuesho/graphql/operation";

export const GraphQLPage = createGraphQLPage({ components: { Operation } });

Headless Usage

To build the page with a custom UI, use the headless entries:

  • @vuesho/graphql/client: createGraphQLRenderer(), and composables for the schema, an operation, its examples and a type's usages
  • @vuesho/graphql/playground: usePlayground(), a request's state, and helpers that send queries and subscriptions

Translations

The generated pages are in each of your site's languages. The UI has language packs for ja, zh-CN and zh-TW, and ui.translations replaces any of its texts:

vuesho.config.ts
createSite(sources, { i18n }).config({
  site: { languages: { cn: { lang: "zh-CN" } } },
  ui: { translations: { cn: { "Arguments(operation page)": "参数" } } }, 
});

Options

createGraphQL()

Prop

Type

staticSource() and dynamicSource()

Prop

Type

per: "file" takes the same options except groupBy and includeOperations. per: "custom" takes toPages() instead, which creates the pages.

graphqlPlugin()

Prop

Type

createGraphQLPage()

Prop

Type

playground's options:

Prop

Type

The parts that components replaces:

Prop

Type

<GraphQLPage>

Prop

Type