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).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
UsegetContextValue() 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:Best Practices
Keep resolvers focused
Keep resolvers focused
Each resolver should do one thing well:
Use TypeScript for type safety
Use TypeScript for type safety
Define types for your GraphQL data:
Avoid N+1 queries
Avoid N+1 queries
Use DataLoader or batch queries to prevent performance issues:
Document your schema
Document your schema
Add descriptions to types and fields:
Testing GraphQL Queries
Using GraphQL Playground
EverShop includes GraphQL Playground (usually athttp://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