Files
payload/docs/graphql/graphql-schema.mdx
Alessio Gravili 254d888b73 docs: add missing types, prefer pnpm, fix various typos, discourage using payload from import (#9847)
- Adds missing types, especially the `Where` type. Will be helpful for
people to see that they can type their queries like that
- Mention pnpm first and prefer pnpm > npm > yarn throughout docs
- Add `payload` to function arguments in examples to discourage people
from doing `import payload from 'payload'`
- PNPM => pnpm, NPM => npm
- Fix some typos
2024-12-09 19:05:09 -07:00

88 lines
2.2 KiB
Plaintext

---
title: GraphQL Schema
label: GraphQL Schema
order: 30
desc: Output your own GraphQL schema based on your collections and globals to a file.
keywords: headless cms, typescript, documentation, Content Management System, cms, headless, javascript, node, react, nextjs
---
In Payload the schema is controlled by your collections and globals. All you need to do is run the generate command and the entire schema will be created for you.
## Schema generation script
Install `@payloadcms/graphql` as a dev dependency:
```bash
pnpm add @payloadcms/graphql -D
```
Run the following command to generate the schema:
```bash
pnpm payload-graphql generate:schema
```
## Custom Field Schemas
For `array`, `block`, `group` and named `tab` fields, you can generate top level reusable interfaces. The following group field config:
```ts
{
type: 'group',
name: 'meta',
interfaceName: 'SharedMeta', // highlight-line
fields: [
{
name: 'title',
type: 'text',
},
{
name: 'description',
type: 'text',
},
],
}
```
will generate:
```ts
// A top level reusable type will be generated
type SharedMeta {
title: String
description: String
}
// And will be referenced inside the generated schema
type Collection1 {
// ...other fields
meta: SharedMeta
}
```
The above example outputs all your definitions to a file relative from your payload config as `./graphql/schema.graphql`. By default, the file will be output to your current working directory as `schema.graphql`.
### Adding an npm script
<Banner type="warning">
<strong>Important</strong>
<br />
Payload needs to be able to find your config to generate your GraphQL schema.
</Banner>
Payload will automatically try and locate your config, but might not always be able to find it. For example, if you are working in a `/src` directory or similar, you need to tell Payload where to find your config manually by using an environment variable.
If this applies to you, create an npm script to make generating types easier:
```json
// package.json
{
"scripts": {
"generate:graphQLSchema": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts payload-graphql generate:schema"
}
}
```
Now you can run `pnpm generate:graphQLSchema` to easily generate your schema.