Ontwerp een Geavanceerd GraphQL Schema met Contextuele Richtlijnen en Best Practices
description
Met deze prompt kan de gebruiker een geavanceerd GraphQL schema ontwerpen dat niet alleen functioneel is, maar ook goed beheersbaar en begrijpelijk binnen teams. Het helpt bij het implementeren van richtlijnen die consistentie, kwaliteit en onderhoudbaarheid bevorderen, wat essentieel is voor grote projecten en samenwerkingen. Zo wordt het risico op fouten verminderd en wordt het ontwikkelproces efficiënter.
prompt
Help me een geavanceerd GraphQL schema te ontwerpen waarbij ik contextuele richtlijnen en best practices kan integreren voor documentatie en schema governance. Mijn domein is: <beschrijf je domein of toepassingsgebied>. Ik wil ondersteuning voor: <specifice ...
try_prompt
generate_helper
disclaimerOnPageApi
tags
ai_answers
provider: openai
model: gpt-4.1-nano
Hier is een voorbeeld van een geavanceerd GraphQL-schema voor een e-commerce platform dat contextuele richtlijnen en best practices integreert voor documentatie en schema governance. Ik zal ook uitleg geven over het gebruik van annotaties, veldbeschrijvingen en het waarborgen van consistentie.
---
### 1. Schema met documentatie en richtlijnen
```graphql
"""
# ProductType vertegenwoordigt een product in het e-commerce platform.
# Naamgevingsconventies:
# - Types beginnen met een hoofdletter (PascalCase).
# - Velden gebruiken camelCase.
# - Gebruik duidelijke en beschrijvende namen.
#
# Veldbeschrijvingen geven extra context voor ontwikkelaars en documentatie.
type Product {
"""
Unieke identifier voor het product.
(Volg UUID-formaat voor consistentie)
"""
id: ID!
"""
Naam van het product.
- Moet omschrijvend en kort zijn.
- Bijvoorbeeld: 'Bluetooth Koptelefoon'
"""
name: String!
"""
Beschrijving van het product.
- Kan markdown of plain tekst bevatten.
"""
description: String
"""
Prijs van het product in centen.
- Gebruik integer voor precisie en eenvoud.
- Bijvoorbeeld, €19,99 wordt 1999.
"""
priceCents: Int!
"""
Beschikbaarheidstatus van het product.
- 'IN_STOCK', 'OUT_OF_STOCK', 'PREORDER'
"""
availabilityStatus: String!
"""
Categorie waartoe het product behoort.
"""
category: Category!
"""
Tags voor het product.
- Gebruik voor zoekoptimalisatie.
"""
tags: [String!]
}
```
### 2. Best practices en governance
- **Naming Conventies**: Consistent gebruik van PascalCase voor types en camelCase voor velden. Bijvoorbeeld, `Product`, `priceCents`.
- **Documentatie**: Elke type en veld krijgt een beschrijving (`""" ... """`). Dit helpt bij automatische documentatie en maakt schema zelf-documenterend.
- **Validaties**: Hoewel GraphQL zelf geen uitgebreide validaties biedt, kunnen custom directives of schema-lagen worden toegevoegd voor regels zoals niet-lege namen, prijs >= 0, etc.
---
### 3. Voorbeeld van extra annotaties en regels voor governance
```graphql
directive @internal on FIELD_DEFINITION | OBJECT
directive @deprecated(reason: String = "No longer supported") on FIELD_DEFINITION | ENUM_VALUE
```
Gebruik deze directives om velden of types te markeren die niet in openbare documentatie moeten verschijnen of verouderd zijn.
---
### 4. Consistentie en kwaliteit waarborgen in teams
- **Schema-linting en tools**: Gebruik tools zoals [GraphQL Schema Linter](https://github.com/za it/graphQL-schema-linter) om schema te controleren op naming, beschrijvingen en best practices.
- **Code reviews**: Stel richtlijnen op voor schema-aanpassingen en voer peer reviews uit.
- **Schema governance documentatie**: Documenteer de conventions en beslissingen in een centrale repository.
- **Automatische documentatie**: Gebruik tools zoals GraphQL Voyager of GraphiQL voor interactieve schema- en documentatieweergave.
- **Versioning en migraties**: Beheer schema wijzingen via versiebeheer (git) en migrate schema's voorzichtig om compatibiliteit te waarborgen.
---
### Samenvatting
Door expliciete veldbeschrijvingen, consistente naamgevingsconventies, en gebruik van directives en linting tools, creëer je een robuust en onderhoudbaar schema dat geschikt is voor grote teams. Documentatie in het schema zelf vergemakkelijkt onboarding en consistentie, terwijl governance richtlijnen en review-processen zorgen voor kwaliteit.
---
Heeft u specifieke functies of onderdelen die u verder uitgewerkt wilt zien?
provider: deepseek
model: deepseek-chat
Of course. Here is a comprehensive guide to designing an advanced GraphQL schema for an E-commerce platform, incorporating best practices for documentation, governance, and large-team collaboration.
### 1. Foundational Principles & Naming Conventions
Consistency in naming is the bedrock of a maintainable schema. It reduces cognitive load and makes the API intuitive.
**Naming Conventions:**
* **Types & Interfaces:** Use `PascalCase`.
* `Product`, `User`, `ShoppingCart`, `PaymentMethod`
* **Fields & Arguments:** Use `camelCase`.
* `product`, `firstName`, `unitPrice`, `itemsInStock`
* **Enums:** Use `PascalCase` for the type and `SCREAMING_SNAKE_CASE` for its values.
* `OrderStatus` with values `PENDING`, `PROCESSING`, `SHIPPED`, `DELIVERED`, `CANCELLED`
* **Queries:** Start with a noun or a `get...` prefix for clarity. Be consistent.
* `products(filter: ...)`, `user(id: "123")`, `getOrderHistory(userId: "123")`
* **Mutations:** Start with a verb describing the action. Follow a `<verb><Noun>` pattern.
* `createProduct`, `updateCart`, `applyDiscountCode`, `cancelOrder`
* **Booleans:** Prefix with `is`, `has`, `can`, etc., to imply a question.
* `isAvailable`, `hasDiscount`, `canCheckout`
---
### 2. Schema Documentation & Descriptions
This is non-negotiable for governance. The GraphQL introspection system makes these descriptions visible in tools like GraphiQL and GraphQL Playground, serving as live, always-up-to-date documentation.
* **Every type, field, argument, and enum value should have a description.**
* Use `"""` (triple-quotes) for multi-line descriptions.
* Describe **what** something is, **why** it's important, and any **constraints**.
**Example: A well-documented `Product` type**
```graphql
"""
A product available for purchase in the store's catalog.
Products can have multiple variants (e.g., size, color).
"""
type Product {
"The unique identifier for the product."
id: ID!
"The human-readable name of the product. Maximum 255 characters."
name: String!
"""
A detailed description of the product, which may include HTML formatting for rich text.
This is displayed on the product detail page.
"""
description: String
"The base price of the product, before any discounts or taxes are applied."
unitPrice: Money!
"""
Indicates if the product is currently available for purchase.
This is a calculated field based on inventory levels and `isActive` status.
"""
isAvailable: Boolean!
"The category this product belongs to. A product can belong to multiple categories."
category: Category!
"A list of images associated with this product. At least one image is required."
images: [ProductImage!]!
"The variants available for this product (e.g., 'Small', 'Red')."
variants: [ProductVariant!]!
}
"""
A monetary value, represented as a decimal string and its currency code.
This ensures type-safe handling of money, avoiding floating-point inaccuracies.
"""
scalar Money
"""
Represents the status of an order in the fulfillment lifecycle.
"""
enum OrderStatus {
"Order has been placed but payment is not yet confirmed."
PENDING
"Payment is confirmed and the order is being prepared for shipment."
PROCESSING
"The order has been shipped to the customer."
SHIPPED
"The order has been successfully delivered."
DELIVERED
"The order was cancelled by the user or the system."
CANCELLED
}
```
---
### 3. Ensuring Consistency & Quality in Teams
A large schema built by many engineers will become inconsistent without automated governance.
**Strategies and Tools:**
1. **Schema Linting (Automated Enforcement):**
* Use a tool like **GraphQL ESLint** (`@graphql-eslint/eslint-plugin`).
* Create a shared linting configuration that enforces your team's rules.
* **Example Rules:**
* `require-description`: Enforces descriptions on all types, fields, etc.
* `alphabetize`: Fields and values must be alphabetized.
* `naming-convention`: Enforces `PascalCase` for types, `camelCase` for fields.
* Run this linting in CI/CD; **fail the build if linting errors exist.**
2. **Schema Contracts & Governance Layer:**
* Use a tool like **GraphQL Hive** or **Apollo Studio**.
* These tools provide a central registry for your schema.
* They can enforce **schema checks** on Pull Requests, preventing breaking changes from being merged. They detect:
* Removing a field that clients are using (breaking change).
* Changing a field's type (breaking change).
* Adding a non-null argument to a field (breaking change).
* They also provide usage analytics, showing which fields are used by which clients, guiding safe deprecation.
3. **The `@deprecated` Directive:**
* Never remove a field outright. Always deprecate it first.
* Provide a clear reason (`reason` argument) so consumers know what to use instead.
* Tools like Apollo Studio will track the usage of deprecated fields, allowing you to remove them safely once usage drops to zero.
**Example of Deprecation:**
```graphql
type Product {
id: ID!
name: String!
unitPrice: Money!
"The price of the product including VAT. Use `unitPrice` and calculate tax client-side for accuracy."
priceWithTax: Money! @deprecated(reason: "Tax calculation is now handled client-side. Use `unitPrice` and the taxRate from the `GeoLocation`.")
}
```
---
### 4. Advanced Schema Design Examples
Here are more examples putting all these concepts together.
**Example 1: Pagination Pattern (Connections)**
Using the Relay Cursor Connections Specification is a best practice for pagination.
```graphql
"""
A connection to a list of `Product` items with pagination information.
"""
type ProductConnection {
"A list of product edges."
edges: [ProductEdge!]!
"Information to aid in pagination."
pageInfo: PageInfo!
}
"""
An edge in a connection, containing a node (the product) and a cursor.
"""
type ProductEdge {
"The item at the end of the edge."
node: Product!
"A cursor for use in pagination."
cursor: String!
}
"""
Information about pagination in a connection.
"""
type PageInfo {
"When paginating forwards, are there more items?"
hasNextPage: Boolean!
"When paginating backwards, are there more items?"
hasPreviousPage: Boolean!
"The cursor of the first item in the result set."
startCursor: String
"The cursor of the last item in the result set."
endCursor: String
}
type Query {
"""
Fetch a paginated list of products from the catalog.
"""
products(
"Returns the first *n* elements from the list."
first: Int
"Returns the elements in the list that come after the specified cursor."
after: String
"Filtering options for the product query."
filter: ProductFilter
): ProductConnection!
}
```
**Example 2: Mutations with Input Types and Client Context**
Input types organize mutation arguments. A `clientMutationId` can help with async operation tracking.
```graphql
"""
Input for the `addItemToCart` mutation.
"""
input AddItemToCartInput {
"The ID of the cart to add the item to."
cartId: ID!
"The ID of the product variant to add."
productVariantId: ID!
"The quantity to add."
quantity: Int! = 1
"""
A unique identifier for the client performing the mutation.
This is passed through and returned in the payload to support client-side tracking of mutations.
"""
clientMutationId: String
}
"""
Payload for the `addItemToCart` mutation.
"""
type AddItemToCartPayload {
"The updated cart after adding the item."
cart: Cart!
"The specific item that was added to the cart."
cartItem: CartItem!
"The same `clientMutationId` that was provided in the input, for reconciliation."
clientMutationId: String
}
type Mutation {
"""
Adds a specific product variant to a shopping cart.
If the item already exists in the cart, the quantities will be merged.
"""
addItemToCart(input: AddItemToCartInput!): AddItemToCartPayload!
}
```
### Summary: Your Governance Checklist
1. **Define & Document Conventions:** Create a shared `SCHEMA_GUIDE.md` for your team.
2. **Automate Linting:** Integrate `graphql-eslint` with rules for descriptions and naming.
3. **Implement Schema Registry:** Use Apollo Studio or GraphQL Hive for change validation and usage tracking.
4. **Never Break Changes:** Use the `@deprecated` directive and rely on your registry's checks to prevent breaking changes from being deployed.
5. **Code Reviews:** Make schema changes a key part of your Pull Request review process, focusing on naming, descriptions, and design patterns.
6. **Versioning:** Prefer progressive evolution (adding new fields, deprecating old ones) over versioned endpoints (e.g., `/v2/graphql`).
By following these practices, your team can collaboratively build a robust, self-documenting, and evolvable GraphQL API that scales with your platform and your team's size.
error: Generation failed [deepseek] prompt_id=2983 locale=nl err=DeepSeek connection/timeout | Generation failed [deepseek] prompt_id=2983 locale=fr err=DeepSeek connection/timeout

