Skip to content

Commit 47d8041

Browse files
ynnojvladar
andauthored
docs(guide): Update GraphCMS data sourcing guide (#27475)
* docs(guide): Update GraphCMS data sourcing guide * style(lint): prettier --write * Update docs/docs/sourcing-from-graphcms.md Co-authored-by: Vladimir Razuvaev <[email protected]> * docs: Add note about beta status Co-authored-by: Vladimir Razuvaev <[email protected]>
1 parent 57fdae5 commit 47d8041

File tree

3 files changed

+167
-85
lines changed

3 files changed

+167
-85
lines changed

docs/docs/images/graphcms-query.png

700 KB
Loading

docs/docs/images/graphcms-schema.png

197 KB
Loading

docs/docs/sourcing-from-graphcms.md

+167-85
Original file line numberDiff line numberDiff line change
@@ -4,158 +4,240 @@ title: Sourcing from GraphCMS
44

55
## Headless the GraphCMS way
66

7-
[GraphCMS](https://graphcms.com?ref="gatsby-headless-docs-top") is a headless CMS that is optimized for working with GraphQL. Content structures like posts, authors, products and more are broken down into content types called "models." These models can then be queried with the familiar GraphQL syntax.
8-
9-
One of the benefits of GraphCMS when working with Gatsby is that it supports GraphQL natively which allows you to test your content queries before even starting your Gatsby project.
7+
[GraphCMS](https://graphcms.com?referrer=gatsby-headless-docs-top) is a GraphQL native Headless Content Management System (Headless CMS) that lets you programmatically deliver content across platforms. With features like an intuitive schema builder, GraphQL mutations API, and out of the box localization, GraphCMS enables you to rapidly build digital projects with your preferred frameworks and languages.
108

119
## Getting started
1210

13-
In this guide you'll create a complete project capable of querying data from GraphCMS.
11+
In this guide you'll create a Gatsby site capable of querying data from GraphCMS.
12+
13+
### Prerequisites
14+
15+
This guide assumes the following:
1416

15-
### Install the boilerplate
17+
- You have an active GraphCMS account
18+
- You've created a new GraphCMS project (preferably using the `Blog Starter` template)
1619

17-
To begin, let's create a Gatsby starter site.
20+
All schema and data references in this guide are from the GraphCMS `Blog Starter` template.
21+
22+
### Create a new Gatsby site
23+
24+
To begin, let's create a new Gatsby site using the default starter.
1825

1926
```shell
2027
gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-default
2128
```
2229

23-
Navigate inside of the project with `cd gatsby-site`.
30+
Once finished, navigate inside of the project with `cd gatsby-site`.
31+
32+
### Add the `gatsby-source-graphcms` plugin
2433

25-
### Add the source plugin
34+
> This plugin is in **beta**. Please use at your own risk!
2635
27-
Additionally, you need the `gatsby-source-graphql` library. Because GraphCMS uses GraphQL natively, you will take advantage of Gatsby's ability to simply stitch two GraphQL APIs together, reducing the time required to transform content. There is no need to use a special gatsby-source-x-cms plugin, the GraphQL source plugin is all you need.
36+
In order to fetch data from your GraphCMS project, you will need to install [`gatsby-source-graphcms`](https://github.com/GraphCMS/gatsby-source-graphcms).
2837

29-
You can install this component with:
38+
You can install this package with:
3039

3140
```shell
32-
# Optionally with `npm install`
33-
npm install gatsby-source-graphql
41+
yarn add gatsby-source-graphcms@next
3442
```
3543

3644
### Configure the plugin
3745

38-
The last step required before you can query your data is to configure the `gatsby-source-graphql` plugin. Open `gatsby-config.js` and add the following object to the plugins array. This example uses an open API from GraphCMS but you will most likely want to replace this with your own API and provide a `fieldName` that makes the most sense to your project. [Here's more information on working with GraphCMS APIs.](https://docs.graphcms.com/docs/api)
46+
The last step required before you can query your data is to configure `gatsby-source-graphcms`. Inside of `gatsby-config.js`, add a new plugin configuration.
47+
48+
> We recommend using environment variables with your GraphCMS `token` and `endpoint` values. You can learn more about using environment variables with Gatsby [here](https://www.gatsbyjs.com/docs/environment-variables).
3949
4050
```js
4151
{
42-
resolve: "gatsby-source-graphql",
43-
options: {
44-
// The top level query type, can be anything you want!
45-
typeName: "GCMS",
46-
// The field you'll query against, can also be anything you want.
47-
fieldName: "gcms",
48-
// Your API endpoint, available from the dashboard and settings window.
49-
// You can use this endpoint that features US mountains for now.
50-
url: "https://api-euwest.graphcms.com/v1/cjm7tab4c04ro019omujh708u/master",
52+
resolve: 'gatsby-source-graphcms',
53+
options: {
54+
// Your GraphCMS API endpoint. Available from your project settings.
55+
endpoint: process.env.GRAPHCMS_ENDPOINT
56+
// A PAT (Permanent Auth Token) for your project. Required if your project is not available publicly, or you want to scope access to a specific content stage (i.e. draft content).
57+
token: process.env.GRAPHCMS_TOKEN
5158
},
5259
},
5360
```
5461

55-
If everything works correctly, you should now have your GraphCMS data added to the Gatsby source API!
56-
57-
### Querying for content
62+
### Inspecting the schema
5863

59-
From the root of your project, run the development environment with `gatsby develop`. Once the server has started and is error free, you should be able to open the following URL in your browser:
64+
Start the Gatsby development environment with `gatsby develop`. Once running, you will be able to access the GraphiQL explorer in your browser:
6065

6166
`http://localhost:8000/___graphql`
6267

63-
This will show you an interface where you can test your new content API.
68+
From here, you will be able to browse the generated GraphQL schema of your Gatsby project.
69+
70+
![GraphCMS Schema](./images/graphcms-schema.png)
71+
72+
The generated Gatsby types for the GraphCMS project models will all be prefixed accordingly. For example, the `Post` model from our GraphCMS project becomes a `GraphCMS_Post` type inside of Gatsby. This prefix can be [configured](https://github.com/GraphCMS/gatsby-source-graphcms#options).
73+
74+
Query fields also follow a similar naming convention and are prefixed by the same value as types. Gatsby will generate two root query fields per type. For example, for our `Post` model Gatsby will generate the following root query fields:
6475

65-
Try running this query:
76+
- `allGraphCmsPost` for querying multiple `Post` entries
77+
- `graphCmsPost` for querying a single `Post` entry
78+
79+
### Querying for content
80+
81+
![GraphCMS Query](./images/graphcms-query.png)
82+
83+
Using the generated schema, we can begin to write GraphQL queries for Gatsby data. Consider the query below, which will return a full list of all available `GraphCMS_Post` nodes.
6684

6785
```graphql
68-
query {
69-
gcms {
70-
mountains {
71-
title
72-
elevation
73-
image {
86+
{
87+
allGraphCmsPost {
88+
nodes {
89+
id
90+
content {
91+
markdown
92+
}
93+
coverImage {
7494
url
7595
}
96+
date
97+
slug
98+
title
7699
}
77100
}
78101
}
79102
```
80103

81-
Again, if everything is working properly, you should see a successful response in the shape of:
82-
83104
```json
84105
{
85106
"data": {
86-
"gcms": {
87-
"mountains": [
107+
"allGraphCmsPost": {
108+
"nodes": [
88109
{
89-
"title": "Denali",
90-
"elevation": 6190,
91-
"image": {
92-
"url": "https://media.graphcms.com//J0rGKdjuSwCk7QrFxVDQ"
93-
}
110+
"id": "Post:ckadrcx4g00pw01525c5d2e56",
111+
"content": {
112+
"markdown": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid ergo? Huius ego nunc auctoritatem sequens idem faciam. Duo Reges: constructio interrete. Sed in rebus apertissimis nimium longi sumus. Itaque his sapiens semper vacabit. Non semper, inquam;\n\n\n\nVerum hoc idem saepe faciamus. Quamquam haec quidem praeposita recte et reiecta dicere licebit.\n\n\n\nAt coluit ipse amicitias. Certe non potest. Bonum incolumis acies: misera caecitas. Quo studio Aristophanem putamus aetatem in litteris duxisse? Idem iste, inquam, de voluptate quid sentit? Facillimum id quidem est, inquam.\n"
113+
},
114+
"coverImage": {
115+
"url": "https://media.graphcms.com/QEg7oQCTEeEjLSEPQJtg"
116+
},
117+
"date": "2020-05-05",
118+
"slug": "technical-seo-with-graphcms",
119+
"title": "Technical SEO with GraphCMS"
94120
},
95121
{
96-
"title": "Mount Elbert",
97-
"elevation": 4401,
98-
"image": {
99-
"url": "https://media.graphcms.com//JNonajrqT6SOyUKgC4L2"
100-
}
122+
"id": "Post:ckadrfuu000pe0148kels2b5e",
123+
"content": {
124+
"markdown": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Id enim natura desiderat. Falli igitur possumus. Negat enim summo bono afferre incrementum diem. Indicant pueri, in quibus ut in speculis natura cernitur.\n\n\n\n# Lorem Ipsum\n\n\n\nNe amores quidem sanctos a sapiente alienos esse arbitrantur. Summus dolor plures dies manere non potest? Expectoque quid ad id, quod quaerebam, respondeas. Non est ista, inquam, Piso, magna dissensio. Respondeat totidem verbis. Non est igitur summum malum dolor.\n\n\n\nHic ambiguo ludimur. Nam Pyrrho, Aristo, Erillus iam diu abiecti. Si longus, levis dictata sunt. Duo Reges: constructio interrete. Deinde dolorem quem maximum?\n"
125+
},
126+
"coverImage": {
127+
"url": "https://media.graphcms.com/gzYJIkMRRHCq0JLDOqgU"
128+
},
129+
"date": "2020-05-01",
130+
"slug": "union-types-and-sortable-relations",
131+
"title": "Union Types and Sortable Relations with GraphCMS"
101132
}
133+
102134
// ...more results
103135
]
104136
}
105137
}
106138
}
107139
```
108140

109-
### Getting content on the page
141+
### Query implementation
142+
143+
Gatsby offers two means of data querying: [page queries](https://www.gatsbyjs.com/docs/page-query) and [static queries](https://www.gatsbyjs.com/docs/static-query).
144+
145+
#### Page query
110146

111-
For the purpose of this tutorial I've removed all the layout, SEO, link or other components that comprise a page in the Gatsby starter. The components are still there and 99% of users will likely want to put them back in once they understand what's happening in the code. You are just looking at the nails for right now, but the hammers, saws and other tools are still in the toolbox. Open the index file located at `src/pages/index.js` and replace the content with this code:
147+
Page queries run at build time and can accept GraphQL variables via page context. As the name suggest, they can only be used on pages and **not** on non-page components.
148+
149+
The resulting data is available via the page props `data` key.
112150

113151
```jsx
114152
import React from "react"
115-
import { StaticQuery } from "gatsby"
116-
117-
const IndexPage = () => (
118-
<StaticQuery
119-
query={graphql`
120-
query {
121-
gcms {
122-
mountains {
123-
title
124-
elevation
153+
import { graphql } from "gatsby"
154+
155+
function IndexPage({ data: { posts } }) {
156+
return (
157+
<ul>
158+
{posts.nodes.map(post => (
159+
<li key={post.id}>
160+
<h3>{post.title}</h3>
161+
</li>
162+
))}
163+
</ul>
164+
)
165+
}
166+
167+
export const pageQuery = graphql`
168+
query IndexPageQuery {
169+
posts: allGraphCmsPost {
170+
nodes {
171+
id
172+
content {
173+
markdown
174+
}
175+
coverImage {
176+
url
177+
}
178+
date
179+
slug
180+
title
181+
}
182+
}
183+
}
184+
`
185+
186+
export default IndexPage
187+
```
188+
189+
#### Static query hook
190+
191+
Static queries also run at build time, but can be used in all components via the `useStaticQuery` hook or `<StaticQuery />` component. However they do **not** accept GraphQL variables.
192+
193+
```jsx
194+
import React from "react"
195+
import { graphql, useStaticQuery } from "gatsby"
196+
197+
function IndexPage() {
198+
const { posts } = useStaticQuery(graphql`
199+
{
200+
posts: allGraphCmsPost {
201+
nodes {
202+
id
203+
content {
204+
markdown
205+
}
206+
coverImage {
207+
url
125208
}
209+
date
210+
slug
211+
title
126212
}
127213
}
128-
`}
129-
render={data => (
130-
<div>
131-
<h1>USA Mountains</h1>
132-
<ul>
133-
{data.gcms.mountains.map(mountain => {
134-
const { title, elevation } = mountain
135-
return (
136-
<li>
137-
<strong>{title}:</strong>
138-
{elevation}
139-
</li>
140-
)
141-
})}
142-
</ul>
143-
</div>
144-
)}
145-
/>
146-
)
214+
}
215+
`)
216+
217+
return (
218+
<ul>
219+
{posts.nodes.map(post => (
220+
<li key={post.id}>
221+
<h3>{post.title}</h3>
222+
</li>
223+
))}
224+
</ul>
225+
)
226+
}
147227

148228
export default IndexPage
149229
```
150230

151-
With this code, you have:
231+
## Learn more
232+
233+
For additional examples of how to query and use GraphCMS data in the context of Gatsby, check out the following references:
152234

153-
1. Added the `StaticQuery` component to a page that allows you to fetch content from the GraphQL API.
154-
2. Fetched some simplified data from the Mountain API, namely the title and elevation.
155-
3. Rendered the list in the StaticQuery's RenderProp called "render".
235+
- [`gatsby-source-graphcms`](https://github.com/GraphCMS/gatsby-source-graphcms)
236+
- [`gatsby-starter-graphcms-blog`](https://github.com/GraphCMS/gatsby-starter-graphcms-blog)
237+
- [`graphcms-examples`](https://github.com/GraphCMS/graphcms-examples)
156238

157239
## Summary
158240

159-
Hopefully you've seen how easy it is to start working with GraphCMS and Gatsby. With projects of all sizes gravitating towards the benefits of the JAM stack, the time has never been better to learn how to work with Gatsby. Adding a content API in the backend with GraphCMS provides a scalable CMS that you can start using within minutes and keep using for the life of your project.
241+
Its extremely easy to start working with GraphCMS and Gatsby. With projects of all sizes transitioning to an API-first approach, creating, enriching, and delivering your content via API to your Gatsby projects is a breeze. Adding a content API in the backend with GraphCMS provides a scalable CMS that you can start using within minutes, and have your project up and running quickly.
160242

161-
[Check out GraphCMS today and build "fast websites", fast!](https://graphcms.com?ref="gatsby-headless-docs-bottom")
243+
Try GraphCMS by [getting started with the free-forever community plan](https://graphcms.com?referrer=gatsby-headless-docs-bottom&utm_source=gatsby&utm_medium=referral)

0 commit comments

Comments
 (0)