Skip to main content

GraphQL API

EverShop uses GraphQL for data fetching in React components. Extensions can add new types, extend existing types, and provide resolvers to fetch data from any source.

What is GraphQL in EverShop?

GraphQL provides:
  • Type-safe data fetching for React components
  • Flexible queries that request exactly the data needed
  • Extensible schema that can be augmented by any extension
  • Automatic data loading for page components
  • Resolver functions that can fetch from databases, APIs, or any data source
Every page component can export a query that automatically fetches data and passes it as props to the component.

Schema Files

GraphQL schemas are defined in .graphql files within extensions:

Creating GraphQL Types

Extending Existing Types

You can add fields to types defined by other extensions or the core system:
extensions/productCatalog/src/graphql/types/ProductExtension/ProductExtension.graphql
Use extend type TypeName to add fields to an existing type. The base type must be defined elsewhere (core or another extension).
Resolvers for extended types:
extensions/productCatalog/src/graphql/types/ProductExtension/ProductExtension.resolvers.js

Resolver Structure

Resolvers are organized by type and field:

Resolver Arguments

Every resolver receives four arguments:

Query Export in Components

Page components can export a GraphQL query that runs automatically:

Context Values

Use getContextValue() to access runtime values:

URL Generation

Get URLs for routes:

Real-World Example: Product Reviews

From the productReviews extension:

Scalar Types

GraphQL supports several scalar types:

Non-null Types

Use ! to mark fields as required:

Lists

Use [] for arrays:

Mutations

Mutations modify data:
With resolvers:

Best Practices

Each resolver should do one thing well:
Define types for your GraphQL data:
Use DataLoader or batch queries to prevent performance issues:
Add descriptions to types and fields:

Testing GraphQL Queries

Using GraphQL Playground

EverShop includes GraphQL Playground (usually at http://localhost:3000/graphql):

Using curl

Next Steps

  • Learn about Extensions for organizing your GraphQL code
  • Understand Routing for REST API alternatives
  • Explore Themes for using GraphQL in page components