# 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](/api-docs/graphql/example/queries/customer) documents a store's schema, with a mock endpoint.

## Setup [#setup]

### Install the Packages [#install-the-packages-step]

```npm
npm i @vuesho/graphql graphql
```

### Add the Source and Plugin [#add-the-source-and-plugin-step]

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

```ts title="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" }), // [!code highlight]
}).plugins(recommendedPreset(), graphqlPlugin());
```

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

### Connect the Playground [#connect-the-playground-step]

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

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

A URL that is a path of the site, like `/api/graphql`, gets the [base path](/deploying#base-path).

### Name the Folder [#name-the-folder-step]

The pages are in an `api` folder in the sidebar. To give the folder a title, add a [meta file](/navigation#folders) to the content folder:

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

## Pages [#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:

<Tabs :items='["Default","includeTypes: true","per: file"]'>
<Tab value="Default">
```files
api
├── queries
│   ├── customer.md
│   ├── orders.md
│   ├── search.md
│   └── node.md
├── mutations
│   ├── createOrder.md
│   └── legacyCreateOrder.md
└── subscriptions
    └── orderUpdated.md
```
</Tab>

<Tab value="includeTypes: true">
```files
api
├── queries
├── mutations
├── subscriptions
├── objects
│   ├── Customer.md
│   ├── ContactInfo.md
│   └── Order.md
├── interfaces
│   └── Node.md
├── unions
│   └── SearchResult.md
├── enums
│   ├── OrderStatus.md
│   └── Role.md
├── inputs
│   ├── OrderFilter.md
│   └── OrderCreateInput.md
└── scalars
    └── DateTime.md
```
</Tab>

<Tab value="per: file">
```files
api
└── store.md
```
</Tab>
</Tabs>

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`:

```ts title="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 [#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:

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

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 title="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 [#schemas]

### Multiple 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:

```ts title="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`:

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

### `input` as a Function [#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:

```ts title="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 [#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](/dynamic-rendering#dynamic-sources):

```ts title="vuesho.config.ts"
createSite({
  docs: docs.toSource(),
  api: graphql.staticSource({ baseDir: "api" }), // [!code --]
  api: graphql.dynamicSource({ baseDir: "api", staleTime: 60_000 }), // [!code ++]
});
```

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

## Playground [#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:

```ts title="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" },
  },
});
```

<Callout type="warn" title="No Secrets in Headers">
`headers` reach the browser and show in the code samples, so never put a secret in them.
</Callout>

`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](/theme#views-and-page-bodies) in your theme:

```ts title="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],
      };
    },
  },
});
```

```ts title="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) }, // [!code highlight]
});
```

### Subscriptions [#subscriptions]

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

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

## Customization [#customization]

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

```ts title="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 [#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:

```ts title="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 });
```

### Cross-Links [#cross-links]

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:

```ts title="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]

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

```vue title="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>
```

```ts title="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`](/cli#vuesho-add):

```npm
npx vuesho add operation --from @vuesho/graphql
```

```ts title="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 [#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 [#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`](/i18n#ui-translations) replaces any of its texts:

```ts title="vuesho.config.ts"
createSite(sources, { i18n }).config({
  site: { languages: { cn: { lang: "zh-CN" } } },
  ui: { translations: { cn: { "Arguments(operation page)": "参数" } } }, // [!code highlight]
});
```

## Options [#options]

### `createGraphQL()` [#creategraphql]

### CreateGraphQLOptions

| Prop          | Type                                                | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `input`       | `DocumentInput<GraphQLSchemaInput>`                 | The schemas: a record of IDs to schemas or to functions that return one, or a list of SDL file paths and URLs, whose IDs are their file names or last URL segments without the extension. A schema is SDL text, an SDL file's path or URL, a list of these merged into one schema with their type extensions, an introspection result, or a `GraphQLSchema`. A function gives them when the schemas are created, and calls `onRead` with each local file it reads. |
| `examples?`   | `string[] \| Record<string, string[]> \| undefined` | GraphQL documents with example operations: file paths, URLs or GraphQL text. Each named operation is an example for the root fields it selects. A record maps schema IDs to their documents, and a list applies to every schema, so each operation in it must be valid in every schema.                                                                                                                                                                            |
| `playground?` | `PlaygroundOptions \| undefined`                    | The interactive playground of the operations of these schemas, shown on their pages when `url` is set. A URL that is a path of the site, like `/api/graphql`, gets the base path.                                                                                                                                                                                                                                                                                  |

### `staticSource()` and `dynamicSource()` [#staticsource-and-dynamicsource]

### GraphQLSourceOptions

| Prop                 | Type                                                                                                              | Description                                                                                                                                                                                                                                                          |
| -------------------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `per?`               | `"item" \| undefined`                                                                                             | A page per operation and per named type. Default: `"item"`                                                                                                                                                                                                           |
| `groupBy?`           | `"kind" \| "none" \| ((entry: Omit<OperationOutput, "path"> \| Omit<TypeOutput, "path">) => string) \| undefined` | How pages are grouped into folders: `"kind"` by kind, like `queries/`, `mutations/` and `objects/`, `"none"` in no folder, or a function that names an entry's folder. Default: `"kind"`                                                                             |
| `includeOperations?` | `boolean \| ((kind: OperationKind, field: GraphQLField<unknown, unknown>) => boolean) \| undefined`               | Generates pages for operations, the fields of the query, mutation and subscription types, or for those a function keeps. Default: `true`                                                                                                                             |
| `name?`              | `NameFn<OperationOutput \| TypeOutput> \| undefined`                                                              |                                                                                                                                                                                                                                                                      |
| `slugify?`           | `((name: string) => string) \| undefined`                                                                         | Turns a name into a URL segment. GraphQL names are already URL-safe, so by default a name stays as is, case included.                                                                                                                                                |
| `includeTypes?`      | `boolean \| ((type: GraphQLNamedType) => boolean) \| undefined`                                                   | Documents named types, like objects, interfaces, unions, enums, input objects and scalars, or those a function keeps: on their own pages with `per: "item"`, or on the page with `per: "file"`. Operation pages show the types they use either way. Default: `false` |
| `baseDir?`           | `string \| undefined`                                                                                             | The folder for the pages in the site's file tree, which sets their URLs.                                                                                                                                                                                             |
| `meta?`              | `boolean \| { folderStyle?: "folder" \| "separator"; } \| undefined`                                              | Generates meta files.                                                                                                                                                                                                                                                |

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

### `graphqlPlugin()` [#graphqlplugin]

### GraphQLPluginOptions

| Prop      | Type                   | Description                                                                                        |
| --------- | ---------------------- | -------------------------------------------------------------------------------------------------- |
| `badges?` | `boolean \| undefined` | Shows each operation's kind in the page tree, with a line through deprecated ones. Default: `true` |

### `createGraphQLPage()` [#creategraphqlpage]

### CreateGraphQLPageOptions

| Prop              | Type                                                                                                                  | Description                                                                                                                                                                                            |
| ----------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `components?`     | `Partial<Partial<PageComponents> & { SchemaUI: Component<SchemaViewProps>; } & GraphQLLayoutComponents> \| undefined` | Replaces parts of the UI, like the ones copied with the CLI of Vuesho.                                                                                                                                 |
| `typeLinks?`      | `((name: string) => string \| undefined) \| undefined`                                                                | Gives a named type's page URL for type links, or `undefined` for a type without its own page.                                                                                                          |
| `operationLinks?` | `((kind: OperationKind, name: string) => string \| undefined) \| undefined`                                           | Gives an operation's page URL for operation links, like the usages on type pages, or `undefined` for an operation without its own page.                                                                |
| `highlighter?`    | `Highlighter \| (() => Highlighter \| PromiseLike<Highlighter>) \| undefined`                                         | The code block highlighter, or a function that loads it. Defaults to `getHighlighter()` from `vuesho/client`: the built-in highlighter with the site's code themes, loaded when a code block needs it. |
| `codeUsages?`     | `CodeUsageGeneratorRegistry \| undefined`                                                                             | The code sample generators for operations. Defaults to cURL, JavaScript, Python, Go, Java, C# and Rust.                                                                                                |
| `playground?`     | `{ fetcher?: (request: PlaygroundRequest, ctx: RenderContext) => Promise<PlaygroundResult>; } \| undefined`           | The interactive playground, beside `playground` of `createGraphQL()`, which gives its endpoint. It shows on operation pages when the endpoint's `url` or `fetcher` is set.                             |

`playground`'s options:

### GraphQLPlaygroundOptions

| Prop       | Type                                                                                           | Description                                                                               |
| ---------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `fetcher?` | `((request: PlaygroundRequest, ctx: RenderContext) => Promise<PlaygroundResult>) \| undefined` | Replaces the fetcher for queries and mutations, for example to send them through a proxy. |

The parts that `components` replaces:

### GraphQLPageComponents

| Prop               | Type                                                     | Description                                                                                                                      |
| ------------------ | -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `Markdown?`        | `Component<{ md: string; }> \| undefined`                | Renders Markdown text from the API specification.                                                                                |
| `CodeBlock?`       | `Component<CodeBlockProps> \| undefined`                 | Its slots `title`, `icon` and `actions` go in its title bar, like those of the code block of `vuesho`.                           |
| `Heading?`         | `Component<{ id: string; depth: number; }> \| undefined` | Its content is the default slot.                                                                                                 |
| `SchemaUI?`        | `Component<SchemaViewProps> \| undefined`                |                                                                                                                                  |
| `Operation?`       | `Component<PageOperationProps> \| undefined`             | Renders one of the page's operations.                                                                                            |
| `TypeDocs?`        | `Component<PageTypeProps> \| undefined`                  | Renders one of the page's named types.                                                                                           |
| `Layout?`          | `Component<PageLayoutProps> \| undefined`                | Wraps the rendered items, with `PageLayoutProps`.                                                                                |
| `OperationLayout?` | `Component<OperationLayoutProps> \| undefined`           | An operation's layout, with the slots `header`, `description`, `deprecated`, `playground`, `arguments`, `returns` and `example`. |
| `TypeLayout?`      | `Component<TypeLayoutProps> \| undefined`                | A named type's layout, with the slots `header`, `definition`, `description`, `fields`, `values`, `usages` and `sdl`.             |
| `Playground?`      | `Component<GraphQLPlaygroundProps> \| undefined`         | Replaces the operations' playground and signature bar, and receives the operation.                                               |

### `<GraphQLPage>` [#graphqlpage]

### GraphQLPageProps

| Prop               | Type                             | Description                                                                                                                                 |
| ------------------ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `schema`           | `string`                         | The ID of the schema in `input`.                                                                                                            |
| `source?`          | `string \| undefined`            | The key in `createSite()` of the source whose pages have the schema, which a page component in Markdown needs on a site of several sources. |
| `items?`           | `GraphQLPageItem[] \| undefined` | The operations and types the page shows.                                                                                                    |
| `showTitle?`       | `boolean \| undefined`           | Shows each item's title as a heading.                                                                                                       |
| `showDescription?` | `boolean \| undefined`           | Shows each item's description as Markdown.                                                                                                  |
