Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: graphql api page and other incremental improvements #17516

Merged
merged 22 commits into from
Sep 24, 2019
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
5be6b9a
update titles
gillkyle Aug 28, 2019
85f6b82
adding descriptions and querying in mdx
gillkyle Aug 29, 2019
561fa82
querying and rendering in mdx
gillkyle Aug 30, 2019
ede442b
generate mdx docs for graphql api page
gillkyle Sep 9, 2019
c604d74
Merge branch 'master' into graphql-workflow
gillkyle Sep 9, 2019
39cee0f
chore: format
Sep 9, 2019
b70bbc6
Merge remote-tracking branch 'upstream/master' into graphql-workflow
Sep 10, 2019
94c4b04
Apply suggestions from code review
gillkyle Sep 16, 2019
6aaff29
add note on one static query per page
gillkyle Sep 16, 2019
860b0fd
add additional note about mixing queries
gillkyle Sep 16, 2019
debc236
Apply suggestions from code review
gillkyle Sep 17, 2019
9a0ca8b
more updates from review suggestions
gillkyle Sep 17, 2019
1c3da69
more code review suggestions
gillkyle Sep 17, 2019
0be44ca
added root fields note and simple query explanation
gillkyle Sep 17, 2019
5144d6b
Apply suggestions from code review
gillkyle Sep 20, 2019
fc4ee16
add info on query structure
gillkyle Sep 20, 2019
42cbfe0
Update docs/docs/graphql-api.md
gillkyle Sep 21, 2019
1c69628
Merge branch 'master' into graphql-workflow
gillkyle Sep 23, 2019
da61d34
Merge branch 'graphql-workflow' of github.com:gatsbyjs/gatsby into gr…
gillkyle Sep 23, 2019
de4f041
Merge remote-tracking branch 'upstream/master' into graphql-workflow
Sep 23, 2019
d6f432d
chore: format
Sep 23, 2019
5bd0c90
Merge remote-tracking branch 'upstream/master' into graphql-workflow
Sep 23, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/docs/creating-slugs-for-pages.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: Creating slugs for pages
title: Creating Slugs for Pages
---

The logic for creating slugs from file names can get tricky, the `gatsby-source-filesystem` plugin ships with a function for creating them.
Expand Down
4 changes: 4 additions & 0 deletions docs/docs/glossary.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,10 @@ Routing is the mechanism for loading the correct content in a website or app bas

## S

### Schema

An exact representation of how data is stored in a system, such as tables and fields in a database or a JSON file structure. In Gatsby, the GraphQL schema expresses all queryable data - or data that components can ask about as part of Gatsby's data layer.

### Server-side

The server-side part of the [client-server relationship](https://en.wikipedia.org/wiki/Client%E2%80%93server_model) refers to operations performed by a computer program which manages access to a centralized resource or service in a computer network. Gatsby uses the server-side technology [Node.js](#nodejs) to compile pages at build time, as opposed to serving them at [browser runtime](#runtime) with [client-side](#client-side) JavaScript. See also: [frontend](#frontend) and [backend](#backend).
Expand Down
266 changes: 266 additions & 0 deletions docs/docs/graphql-api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
---
title: GraphQL API
gillkyle marked this conversation as resolved.
Show resolved Hide resolved
tableOfContentsDepth: 2
---

import { GraphqlApiQuery } from "../../www/src/components/api-reference/doc-static-queries"
import APIReference from "../../www/src/components/api-reference"

A great advantage of Gatsby is a built-in data layer that combines any and all data sources you configure. Data is collected at [build time](/docs/glossary#build) and automatically assembled into a [schema](/docs/glossary#schema) that defines how data can be queried throughout your site.

This doc serves as a reference for GraphQL features built into Gatsby, including methods for querying and sourcing data, and customizing GraphQL for your site's needs.

## Getting Started with GraphQL

GraphQL is available in Gatsby without a special install: a schema is automatically inferred and created when you run `gatsby develop` or `gatsby build`. When the site compiles, the data layer can be [explored](/docs/running-queries-with-graphiql/) at: `http://localhost:8000/___graphql`

## Sourcing Data

Data needs to be [sourced](/docs/content-and-data/) — or added to the GraphQL schema — to be queried and pulled into pages using GraphQL. Gatsby uses [source plugins](/plugins/?=gatsby-source) to pull in data.

**Note**: GraphQL isn't required: you can still [use Gatsby without GraphQL](/docs/using-gatsby-without-graphql/).

Sourcing data with an existing plugin requires installing necessary packages and adding the plugin to the plugins array in the `gatsby-config` with any optional configurations. To source data from the filesystem for use with GraphQL, such as Markdown files, images, and more, refer to the [filesystem data sourcing docs](/docs/sourcing-from-the-filesystem/) and [recipes](/docs/recipes/#5-sourcing-data).

For instructions on installing plugins from npm, refer to the instructions in the docs on [using a plugin](/docs/using-a-plugin-in-your-site/).

You can also [create custom plugins](/docs/creating-plugins/) to fit your own use cases and pull in data however you want.

## Query components and hooks

Data can be queried inside pages, components, or the `gatsby-node.js` file, using one of these options:
gillkyle marked this conversation as resolved.
Show resolved Hide resolved

- The `pageQuery` component
- The `StaticQuery` component
- The `useStaticQuery` hook

**Note**: Because of how Gatsby processes GraphQL queries, you can't mix page queries and static queries in the same file. You also can't have multiple page queries or static queries in one file.
gillkyle marked this conversation as resolved.
Show resolved Hide resolved

For information on page and non-page components as they relate to queries, check out the docs guide on [building with components](/docs/building-with-components/#how-does-gatsby-use-react-components)

### `pageQuery`

`pageQuery` is a built-in component that retrieves information from the data layer in Gatsby pages. You can have one page query per page. It can take GraphQL arguments for variables in your queries.

A [page is made in Gatsby](/docs/page-creation/) by any React component in the `src/pages` folder, or by calling the `createPage` action and using a component in the `createPage` options -- meaning a `pageQuery` won't work in any component, only components that meet this criteria.

Also, refer to the [guide on querying data in pages with page query](/docs/page-query/).

#### Params

A page query isn't a method, but rather an exported variable that's assigned a `graphql` string and a valid query block as its value:

```javascript
export const pageQuery = graphql`
query HomePageQuery {
site {
siteMetadata {
description
}
}
}
`
```

**Note**: the query exported in a `const` doesn't need to be named `pageQuery`. More importantly, Gatsby looks for an exported `graphql` string from the file.

#### Returns

When included in a page component file, a page query returns a data object that is passed automatically to the component as a prop.

```javascript
// highlight-start
const HomePage = ({ data }) => {
// highlight-end
return (
<div>
Hello!
{data.site.siteMetadata.description} // highlight-line
</div>
)
}
```

### `StaticQuery`

StaticQuery is a built-in component for retrieving data from Gatsby’s data layer in non-page components, such as a header, navigation, or any other child component.

You can only have one `StaticQuery` per page: in order to include the data you need from multiple sources, you can use one query with multiple [root fields](/docs/graphql-concepts/#query-fields). It cannot take variables as arguments.

Also, refer to the [guide on querying data in components with static query](/docs/static-query/).

#### Params

The `StaticQuery` component takes two values as props in JSX:

- `query`: a `graphql` query string
- `render`: a component with access to the data returned

```jsx
<StaticQuery
query={graphql` //highlight-line
query HeadingQuery {
site {
siteMetadata {
title
}
}
}
`}
render={(
data //highlight-line
) => (
<header>
<h1>{data.site.siteMetadata.title}</h1>
</header>
)}
/>
```

#### Returns

The StaticQuery component returns `data` in a `render` prop:

```jsx
<StaticQuery
// ...
// highlight-start
render={data => (
<header>
<h1>{data.site.siteMetadata.title}</h1>
</header>
)}
// highlight-end
/>
```

### `useStaticQuery`

The `useStaticQuery` hook can be used similar to `StaticQuery` in any component or page, but doesn't require the use of a component and render prop.

Because it is a React hook, the [rules of hooks](https://reactjs.org/docs/hooks-rules.html) apply and you'll need to use it with React and ReactDOM version 16.8.0 or later. Because of how queries currently work in Gatsby, only one instance of `useStaticQuery` is supported in each file.

Also, refer to the [guide on querying data in components with useStaticQuery](/docs/use-static-query/).

#### Params

The `useStaticQuery` hook takes one argument:

- `query`: a `graphql` query string

```jsx
const data = useStaticQuery(graphql`
query HeaderQuery {
site {
siteMetadata {
title
}
}
}
`)
```

#### Returns

The `useStaticQuery` hook returns data in an object:

```jsx
const data = useStaticQuery(graphql`
query HeaderQuery {
site {
siteMetadata {
title
}
}
}
`)
return (
// highlight-start
<header>
<h1>{data.site.siteMetadata.title}</h1>
</header>
// highlight-end
)
```

gillkyle marked this conversation as resolved.
Show resolved Hide resolved
## Query structure

Queries are written in the same shape you want data returned in. How you source data will determine the names of fields that you can query on, based on the nodes they add to the GraphQL schema.

For understanding the parts of a query refer to the [conceptual guide](/docs/graphql-concepts/#understanding-the-parts-of-a-query).

### GraphQL query arguments

GraphQL queries can take arguments to alter how the data is returned. The logic for these arguments is handled internally by Gatsby. Arguments can be passed in to fields at any level of the query.

Different nodes can take different arguments based off of the nature of the node.

The arguments you can pass to collections (like arrays or long lists of data - ex. `allFile`, or `allMdx`) are:

- [`filter`](/docs/graphql-reference#filter)
- [`limit`](/docs/graphql-reference#limit)
- [`sort`](/docs/graphql-reference#sort)
- [`skip`](/docs/graphql-reference#skip)

The arguments you can pass to a `date` field are:

- [`formatString`](/docs/graphql-reference#dates)
- [`locale`](/docs/graphql-reference#dates)

The arguments you can pass to an `excerpt` field are:

- [`pruneLength`](/docs/graphql-reference#excerpt)
- [`truncate`](/docs/graphql-reference#excerpt)

### Graphql query operations

Other built-in configurations can be used in queries

- [`Alias`](/docs/graphql-reference#alias)
- [`Group`](/docs/graphql-reference#group)

gillkyle marked this conversation as resolved.
Show resolved Hide resolved
## Query fragments

Fragments allow you to reuse parts of GraphQL queries. They also allow you to split up complex queries into smaller, easier to understand components.

For more information, check out the docs guide on [using fragments in Gatsby](/docs/using-fragments/).

### List of Gatsby fragments

Some fragments come included in Gatsby plugins, such as fragments for returning optimized image data in various formats with `gatsby-image` and `gatsby-transformer-sharp`, or data fragments with `gatsby-source-contentful`.

#### Image Sharp fragments

The following fragments are available in any site with `gatsby-transformer-sharp` installed and included in your `gatsby-config.js`.

Information on querying with these fragments is also listed in-depth in the [Gatsby Image API docs](/docs/gatsby-image/), including options like resizing and recoloring.

<GraphqlApiQuery>
{data => (
<APIReference
relativeFilePath={data.transformerSharp.nodes[0].relativePath}
docs={data.transformerSharp.nodes[0].childrenDocumentationJs}
/>
)}
</GraphqlApiQuery>

#### Contentful fragments

The following fragments are available in any site with `gatsby-source-contentful` installed and included in your `gatsby-config.js`. These fragments generally mirror the fragments outlined in the `gatsby-transformer-sharp` package.

<GraphqlApiQuery>
{data => (
<APIReference
relativeFilePath={data.contentfulFragments.nodes[0].relativePath}
docs={data.contentfulFragments.nodes[0].childrenDocumentationJs}
/>
)}
</GraphqlApiQuery>

_**Note**: the above fragments are from officially maintained Gatsby starters; other plugins like `gatsby-source-datocms` and `gatsby-source-sanity` ship with fragments of their own. A list of those fragments can be found in the [`gatsby-image` README](/packages/gatsby-image#fragments)._

## Advanced Customizations

It's possible to customize sourced data in the GraphQL layer and create relationships between nodes with the [Gatsby Node APIs](/docs/node-apis/).

The GraphQL schema can be customized for more advanced use cases: read more about it in the [schema customization API docs](/docs/schema-customization/).
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: Querying Data with GraphQL
title: GraphQL Concepts
---

There are many options for loading data into React components. One of the most
Expand Down Expand Up @@ -84,6 +84,24 @@ immediately start using it.

_Note:_ To run GraphQL queries in non-page components you'll need to use [Gatsby's Static Query feature](/docs/static-query/).

### Understanding the parts of a query

The following diagram shows a GraphQL query, with each word highlighted in a color corresponding to its name on the legend:

![GraphQL query diagram](./images/basic-query.png)

#### Query Operation Type

The diagram marks the word `query` as the "Operation Type", for Gatsby's uses the only operation type you will deal with is `query`, this can be omitted from your queries if you prefer (like in the above example).

#### Operation Name

`SiteInformation` is marked as the "Operation Name", which is a unique name that you assign to a query yourself. This is similar to how you would name a function or a variable, and like a function this can be omitted if you would rather the query be anonymous.

#### Query Fields

The four words `site`, `id`, `siteMetadata`, and `title` are marked as "Fields". Any top-level fields -- like `site` in the diagram -- are sometimes referred to as **root level fields**, though the name doesn't signify functional significance as all fields in GraphQL queries behave the same.

## How to learn GraphQL

Your experience developing with Gatsby might be the first time you've seen GraphQL! We hope you love it as much
Expand Down Expand Up @@ -341,6 +359,7 @@ export const query = graphql`
## Further reading

- [Why Gatsby Uses GraphQL](/docs/why-gatsby-uses-graphql/)
- [The Anatomy of a GraphQL Query](https://blog.apollographql.com/the-anatomy-of-a-graphql-query-6dffa9e9e747)

### Getting started with GraphQL

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/graphql-reference.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: GraphQL Reference
title: GraphQL Query Options Reference
---

## Intro
Expand Down
Binary file added docs/docs/images/basic-query.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 2 additions & 1 deletion docs/docs/schema-customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ The following guide walks through some examples to showcase the API.
> created by automatic type inference, developers optimizing builds for larger
> sites, and anyone interested in customizing Gatsby's schema generation.
> As such, the guide assumes that you're somewhat familiar with GraphQL types
> and with using Gatsby's Node APIs.
> and with using Gatsby's Node APIs. For a higher level approach to using
> Gatsby with GraphQL, refer to the [API reference](/docs/graphql-api/).

## Explicitly defining data types

Expand Down
2 changes: 2 additions & 0 deletions packages/gatsby-image/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,8 @@ Their fragments are:
- `GatsbySanityImageFluid`
- `GatsbySanityImageFluid_noBase64`

_Links to source code for fragment fields of official Gatsby plugins can be found in the [Gatsby GraphQL API](/docs/graphql-api/)_

If you don't want to use the blur-up effect, choose the fragment with `noBase64`
at the end. If you want to use the traced placeholder SVGs, choose the fragment
with `tracedSVG` at the end.
Expand Down
Loading