89 lines
2.2 KiB
Plaintext
89 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">
|
|
**Important**
|
|
|
|
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.
|