🎯 Exemplos recomendados
Balanced sample collections from various categories for you to explore
Exemplos de Linguagem de Consulta GraphQL
Exemplos de linguagem de consulta GraphQL de consultas simples a esquemas complexos e resolvers
⚙️ Consulta Básica
🟢 simple
Exemplos simples de consultas GraphQL
# Basic GraphQL Query Examples
# =================================
# Simple field query
query GetUser {
user(id: "1") {
id
name
email
}
}
# Query with arguments
query GetPosts {
posts(limit: 10, offset: 0) {
id
title
content
publishedAt
}
}
# Query with variables
query GetPostsByCategory($category: String!, $limit: Int = 5) {
posts(category: $category, limit: $limit) {
id
title
author {
name
avatar
}
createdAt
}
}
# Variables for the above query
{
"category": "technology",
"limit": 10
}
# Nested query
query GetUserWithPosts {
user(id: "1") {
id
name
email
posts {
id
title
content
comments {
id
text
author {
name
}
}
}
}
}
# Query with aliases
query GetUserData {
firstUser: user(id: "1") {
id
name
email
}
secondUser: user(id: "2") {
id
name
email
}
}
# Query with fragments
query GetUsersWithPosts {
users {
...userDetails
posts {
...postDetails
}
}
}
fragment userDetails on User {
id
name
email
avatar
}
fragment postDetails on Post {
id
title
content
publishedAt
likes
}
# Query with directives
query GetPostsWithDirectives {
posts {
id
title
content @include(if: $showContent)
publishedAt @skip(if: $hideDates)
author {
name
email @include(if: $showEmail)
}
}
}
# Variables for directives
{
"showContent": true,
"hideDates": false,
"showEmail": false
}
⚙️ Esquema de Sistema de Usuários
🟡 intermediate
Esquema GraphQL completo para sistema de gerenciamento de usuários
# User Management System GraphQL Schema
# ========================================
# Schema definition
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
# Base scalar types
scalar DateTime
scalar Email
scalar URL
scalar JSON
# User type
type User {
id: ID!
email: Email!
username: String!
firstName: String!
lastName: String!
avatar: URL
bio: String
role: UserRole!
status: UserStatus!
profile: UserProfile
preferences: UserPreferences
permissions: [Permission!]!
createdAt: DateTime!
updatedAt: DateTime!
lastLoginAt: DateTime
}
# User profile with additional details
type UserProfile {
userId: ID!
phone: String
dateOfBirth: DateTime
address: Address
socialLinks: [SocialLink!]
settings: UserSettings
}
# Address type
type Address {
street: String!
city: String!
state: String!
country: String!
postalCode: String!
coordinates: Coordinates
}
type Coordinates {
latitude: Float!
longitude: Float!
}
# Social media links
type SocialLink {
platform: SocialPlatform!
url: URL!
username: String
}
# User preferences
type UserPreferences {
theme: Theme!
language: String!
timezone: String!
notifications: NotificationPreferences!
privacy: PrivacySettings!
}
# Notification preferences
type NotificationPreferences {
email: Boolean!
push: Boolean!
sms: Boolean!
marketing: Boolean!
}
# Privacy settings
type PrivacySettings {
profileVisibility: VisibilityLevel!
showEmail: Boolean!
showPhone: Boolean!
allowSearch: Boolean!
}
# User settings
type UserSettings {
twoFactorEnabled: Boolean!
emailVerified: Boolean!
phoneVerified: Boolean!
sessionTimeout: Int!
}
# User roles and permissions
enum UserRole {
ADMIN
MODERATOR
USER
GUEST
}
enum UserStatus {
ACTIVE
INACTIVE
SUSPENDED
PENDING_VERIFICATION
}
enum SocialPlatform {
TWITTER
FACEBOOK
LINKEDIN
INSTAGRAM
GITHUB
}
enum Theme {
LIGHT
DARK
AUTO
}
enum VisibilityLevel {
PUBLIC
FRIENDS
PRIVATE
}
type Permission {
id: ID!
name: String!
description: String
module: String!
}
# Input types
input CreateUserInput {
email: Email!
username: String!
firstName: String!
lastName: String!
password: String!
role: UserRole = USER
}
input UpdateUserInput {
firstName: String
lastName: String
bio: String
avatar: URL
phone: String
dateOfBirth: DateTime
}
input UserFilterInput {
role: UserRole
status: UserStatus
search: String
createdAfter: DateTime
createdBefore: DateTime
}
input AddressInput {
street: String!
city: String!
state: String!
country: String!
postalCode: String!
}
# Authentication types
type AuthPayload {
token: String!
refreshToken: String!
user: User!
expiresIn: Int!
}
type RefreshTokenPayload {
token: String!
expiresIn: Int!
}
input LoginInput {
email: Email!
password: String!
}
input RegisterInput {
email: Email!
username: String!
firstName: String!
lastName: String!
password: String!
}
input ChangePasswordInput {
currentPassword: String!
newPassword: String!
}
input ResetPasswordInput {
token: String!
newPassword: String!
}
# Query root
type Query {
# User queries
me: User
user(id: ID!): User
users(filter: UserFilterInput, first: Int, after: String): UserConnection!
searchUsers(query: String!, first: Int): [User!]!
# Authentication queries
verifyEmail(token: String!): Boolean!
isUsernameAvailable(username: String!): Boolean!
isEmailAvailable(email: Email!): Boolean!
}
# Mutation root
type Mutation {
# Authentication mutations
register(input: RegisterInput!): AuthPayload!
login(input: LoginInput!): AuthPayload!
logout: Boolean!
refreshToken: RefreshTokenPayload!
changePassword(input: ChangePasswordInput!): Boolean!
forgotPassword(email: Email!): Boolean!
resetPassword(input: ResetPasswordInput!): Boolean!
verifyEmailToken(token: String!): Boolean!
# User mutations
updateProfile(input: UpdateUserInput!): User!
updateAvatar(avatar: URL!): User!
updatePreferences(preferences: UserPreferencesInput!): User!
updateAddress(address: AddressInput!): User!
addSocialLink(platform: SocialPlatform!, url: URL!): User!
removeSocialLink(platform: SocialPlatform!): User!
# Admin mutations
updateUserRole(userId: ID!, role: UserRole!): User!
updateUserStatus(userId: ID!, status: UserStatus!): User!
deleteUser(userId: ID!): Boolean!
}
# Subscription root
type Subscription {
# User subscriptions
userUpdated(userId: ID!): User!
userStatusChanged(userId: ID!): User!
# Authentication subscriptions
userLoggedIn(userId: ID!): User!
userLoggedOut(userId: ID!): User!
}
# Relay pagination types
type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type UserEdge {
node: User!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
# Input for user preferences (nested object)
input UserPreferencesInput {
theme: Theme
language: String
timezone: String
notifications: NotificationPreferencesInput
privacy: PrivacySettingsInput
}
input NotificationPreferencesInput {
email: Boolean
push: Boolean
sms: Boolean
marketing: Boolean
}
input PrivacySettingsInput {
profileVisibility: VisibilityLevel
showEmail: Boolean
showPhone: Boolean
allowSearch: Boolean
}
⚙️ Operações de Mutação
🟡 intermediate
Mutações GraphQL para modificar e criar dados
# GraphQL Mutations Examples
# =============================
# User registration mutation
mutation RegisterUser($input: RegisterInput!) {
register(input: $input) {
token
refreshToken
user {
id
email
username
firstName
lastName
role
createdAt
}
expiresIn
}
}
# Variables for registration
{
"input": {
"email": "[email protected]",
"username": "johndoe",
"firstName": "John",
"lastName": "Doe",
"password": "SecurePassword123!"
}
}
# User login mutation
mutation Login($input: LoginInput!) {
login(input: $input) {
token
refreshToken
user {
id
email
username
firstName
lastName
lastLoginAt
}
expiresIn
}
}
# Variables for login
{
"input": {
"email": "[email protected]",
"password": "SecurePassword123!"
}
}
# Create product mutation
mutation CreateProduct($input: CreateProductInput!) {
createProduct(input: $input) {
id
sku
name
description
price
status
category {
id
name
}
images {
id
url
isPrimary
}
variants {
id
sku
title
price
inventoryQuantity
}
createdAt
}
}
# Variables for creating product
{
"input": {
"sku": "TSHIRT-001",
"name": "Premium Cotton T-Shirt",
"description": "High quality 100% organic cotton t-shirt",
"price": "29.99",
"categoryId": "1",
"images": [
{
"url": "https://example.com/tshirt-front.jpg",
"altText": "Front view of premium t-shirt",
"position": 1,
"isPrimary": true
},
{
"url": "https://example.com/tshirt-back.jpg",
"altText": "Back view of premium t-shirt",
"position": 2,
"isPrimary": false
}
],
"variants": [
{
"sku": "TSHIRT-001-S-BLK",
"title": "Small Black",
"price": "29.99",
"option1": "Small",
"option2": "Black",
"inventoryQuantity": 50
},
{
"sku": "TSHIRT-001-M-BLK",
"title": "Medium Black",
"price": "29.99",
"option1": "Medium",
"option2": "Black",
"inventoryQuantity": 75
}
],
"tags": ["clothing", "cotton", "eco-friendly", "premium"]
}
}
# Update product mutation
mutation UpdateProduct($productId: ID!, $input: UpdateProductInput!) {
updateProduct(id: $productId, input: $input) {
id
name
description
price
status
updatedAt
}
}
# Variables for updating product
{
"productId": "1",
"input": {
"name": "Premium Organic Cotton T-Shirt",
"price": "34.99",
"description": "High quality 100% GOTS certified organic cotton t-shirt with reinforced stitching"
}
}
# Add to cart mutation
mutation AddToCart($input: AddToCartInput!) {
addToCart(input: $input) {
id
items {
id
product {
id
name
price
}
variant {
id
title
sku
}
quantity
unitPrice
totalPrice
}
subtotal
totalAmount
currency
updatedAt
}
}
# Variables for adding to cart
{
"input": {
"productId": "1",
"variantId": "2",
"quantity": 2,
"customizations": [
{
"name": "Size",
"value": "Large"
},
{
"name": "Color",
"value": "Navy Blue"
}
]
}
}
# Create order from cart
mutation CreateOrder($input: CreateOrderInput!) {
createOrder(input: $input) {
id
orderNumber
status
totalAmount
currency
items {
id
product {
name
}
quantity
unitPrice
totalPrice
}
shippingAddress {
firstName
lastName
address1
city
country
postalCode
}
createdAt
}
}
# Variables for creating order
{
"input": {
"cartId": "cart_123",
"shippingAddress": {
"type": "SHIPPING",
"firstName": "John",
"lastName": "Doe",
"address1": "123 Main Street",
"city": "New York",
"province": "NY",
"country": "United States",
"postalCode": "10001",
"phone": "+1-555-0123"
},
"billingAddress": {
"type": "BILLING",
"firstName": "John",
"lastName": "Doe",
"address1": "123 Main Street",
"city": "New York",
"province": "NY",
"country": "United States",
"postalCode": "10001",
"phone": "+1-555-0123"
},
"paymentMethod": {
"gateway": "stripe",
"token": "tok_1A2b3C4d5e6f",
"savePaymentMethod": true
}
}
}
# Update customer profile
mutation UpdateProfile($input: UpdateCustomerInput!) {
updateProfile(input: $input) {
id
firstName
lastName
phone
birthday
gender
updatedAt
}
}
# Variables for updating profile
{
"input": {
"firstName": "Johnathan",
"lastName": "Doe-Smith",
"phone": "+1-555-0123",
"birthday": "1990-01-15T00:00:00Z",
"gender": "MALE"
}
}
# Add customer address
mutation AddAddress($input: AddressInput!) {
addAddress(input: $input) {
id
addresses {
id
type
firstName
lastName
address1
city
country
postalCode
isDefault
}
}
}
# Variables for adding address
{
"input": {
"type": "SHIPPING",
"firstName": "John",
"lastName": "Doe",
"company": "Acme Corp",
"address1": "456 Business Ave",
"address2": "Suite 789",
"city": "San Francisco",
"province": "CA",
"country": "United States",
"postalCode": "94102",
"phone": "+1-555-0456"
}
}
# Create product review
mutation CreateReview($productId: ID!, $input: CreateReviewInput!) {
createReview(productId: $productId, input: $input) {
id
product {
name
}
customer {
firstName
lastName
}
rating
title
content
images
verified
createdAt
}
}
# Variables for creating review
{
"productId": "1",
"input": {
"rating": 5,
"title": "Amazing Quality!",
"content": "This is exactly what I was looking for. The material is soft and comfortable, and the fit is perfect. Highly recommend!",
"images": [
"https://example.com/review-image1.jpg",
"https://example.com/review-image2.jpg"
]
}
}
# Change password
mutation ChangePassword($input: ChangePasswordInput!) {
changePassword(input: $input)
}
# Variables for changing password
{
"input": {
"currentPassword": "OldPassword123!",
"newPassword": "NewSecurePassword456!"
}
}
# Apply discount code to cart
mutation ApplyDiscountCode($code: String!) {
applyDiscountCode(code: $code) {
id
subtotal
discountAmount
totalAmount
appliedDiscounts {
code
amount
type
description
}
}
}
# Variables for discount code
{
"code": "SUMMER2024"
}
# Update cart item quantity
mutation UpdateCartItem($itemId: ID!, $quantity: Int!) {
updateCartItem(itemId: $itemId, quantity: $quantity) {
id
items {
id
quantity
totalPrice
}
subtotal
totalAmount
updatedAt
}
}
# Variables for updating cart item
{
"itemId": "item_123",
"quantity": 3
}
# Cancel order
mutation CancelOrder($orderId: ID!, $reason: String!) {
cancelOrder(orderId: $orderId, reason: $reason) {
id
orderNumber
status
cancelledAt
}
}
# Variables for canceling order
{
"orderId": "order_456",
"reason": "Customer requested cancellation"
}
# Multiple mutations in one request
mutation UpdateProfileAndAddAddress(
$profileInput: UpdateCustomerInput!,
$addressInput: AddressInput!
) {
updateProfile(input: $profileInput) {
id
firstName
lastName
updatedAt
}
addAddress(input: $addressInput) {
id
addresses {
id
type
address1
city
isDefault
}
}
}
# Variables for multiple mutations
{
"profileInput": {
"firstName": "John",
"lastName": "Doe",
"phone": "+1-555-0123"
},
"addressInput": {
"type": "SHIPPING",
"firstName": "John",
"lastName": "Doe",
"address1": "123 Main Street",
"city": "New York",
"country": "United States",
"postalCode": "10001"
}
}
⚙️ Funcionalidade de Assinatura
🟡 intermediate
Assinaturas GraphQL para atualizações de dados em tempo real
# GraphQL Subscriptions Examples
# ================================
# Subscribe to user updates
subscription UserUpdated($userId: ID!) {
userUpdated(userId: $userId) {
id
username
email
status
lastLoginAt
updatedAt
}
}
# Variables for user subscription
{
"userId": "123"
}
# Subscribe to order status changes
subscription OrderUpdated($orderId: ID!) {
orderUpdated(orderId: $orderId) {
id
orderNumber
status
fulfillmentStatus
trackingInfo {
number
company
url
}
updatedAt
events {
type
message
createdAt
}
}
}
# Variables for order subscription
{
"orderId": "order_456"
}
# Subscribe to new orders for a customer
subscription NewOrderForCustomer($customerId: ID!) {
orderCreated(customerId: $customerId) {
id
orderNumber
totalAmount
status
items {
product {
name
image {
url
}
}
quantity
totalPrice
}
createdAt
}
}
# Variables for customer order subscription
{
"customerId": "customer_789"
}
# Subscribe to cart updates
subscription CartUpdated($cartId: ID!) {
cartUpdated(cartId: $cartId) {
id
items {
id
product {
id
name
price
}
variant {
id
title
}
quantity
totalPrice
}
subtotal
totalAmount
appliedDiscounts {
code
amount
description
}
updatedAt
}
}
# Variables for cart subscription
{
"cartId": "cart_123"
}
# Subscribe to product inventory changes
subscription ProductInventoryUpdate($productId: ID!) {
lowStockAlert(productId: $productId) {
id
name
sku
inventory {
quantity
available
lowStockThreshold
trackQuantity
}
status
updatedAt
}
}
# Variables for product inventory subscription
{
"productId": "product_456"
}
# Subscribe to product updates
subscription ProductUpdated($productId: ID!) {
productUpdated(productId: $productId) {
id
name
price
status
images {
url
isPrimary
}
inventory {
quantity
available
}
updatedAt
}
}
# Variables for product update subscription
{
"productId": "product_789"
}
# Subscribe to user login/logout events
subscription UserAuthEvents($userId: ID!) {
userLoggedIn(userId: $userId) {
id
username
email
lastLoginAt
loginInfo {
ipAddress
userAgent
location {
city
country
}
}
}
userLoggedOut(userId: $userId) {
id
username
logoutAt
sessionInfo {
sessionId
duration
}
}
}
# Variables for auth events subscription
{
"userId": "user_123"
}
# Subscribe to order fulfillment updates
subscription OrderFulfillment($orderId: ID!) {
orderUpdated(orderId: $orderId) {
id
orderNumber
fulfillmentStatus
fulfillments {
id
status
trackingInfo {
company
number
url
}
items {
product {
name
}
quantity
}
shippedAt
deliveredAt
}
}
}
# Variables for order fulfillment subscription
{
"orderId": "order_456"
}
# Subscribe to real-time notifications
subscription UserNotifications($userId: ID!) {
notificationAdded(userId: $userId) {
id
type
title
message
data
read
createdAt
actionUrl
}
}
# Variables for notifications subscription
{
"userId": "user_123"
}
# Subscribe to live chat messages
subscription ChatMessages($chatRoomId: ID!) {
messageAdded(chatRoomId: $chatRoomId) {
id
sender {
id
username
avatar
}
content
timestamp
type
metadata
}
}
# Variables for chat subscription
{
"chatRoomId": "room_456"
}
# Subscribe to live auction bids
subscription AuctionBids($auctionId: ID!) {
bidPlaced(auctionId: $auctionId) {
id
amount
bidder {
id
username
avatar
}
timestamp
isWinning
auctionStatus
}
}
# Variables for auction subscription
{
"auctionId": "auction_123"
}
# Subscribe to live stock prices
subscription StockPrices($symbols: [String!]!) {
priceUpdate(symbols: $symbols) {
symbol
price
change
changePercent
volume
timestamp
marketOpen
}
}
# Variables for stock prices subscription
{
"symbols": ["AAPL", "GOOGL", "MSFT", "TSLA"]
}
# Subscribe to system status updates
subscription SystemStatus {
systemStatusChanged {
status
services {
name
status
responseTime
lastCheck
}
message
severity
timestamp
}
}
# Subscribe to multi-user collaboration
subscription DocumentUpdates($documentId: ID!) {
documentUpdated(documentId: $documentId) {
id
content
operation
position
length
author {
id
username
color
}
timestamp
version
}
}
# Variables for document collaboration subscription
{
"documentId": "doc_123"
}
# Client-side subscription examples using Apollo Client
# ===================================================
import { gql, useSubscription } from '@apollo/client';
// React component for real-time order updates
const OrderTracker = ({ orderId }) => {
const { data, loading, error } = useSubscription(ORDER_UPDATED_SUBSCRIPTION, {
variables: { orderId },
onSubscriptionData: ({ subscriptionData }) => {
console.log('Order updated:', subscriptionData.data);
// Handle order update (show notification, update UI, etc.)
}
});
if (loading) return <p>Loading order updates...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h3>Order Status: {data?.orderUpdated?.status}</h3>
{data?.orderUpdated?.trackingInfo && (
<p>Tracking: {data.orderUpdated.trackingInfo.company} {data.orderUpdated.trackingInfo.number}</p>
)}
</div>
);
};
const ORDER_UPDATED_SUBSCRIPTION = gql`
subscription OrderUpdated($orderId: ID!) {
orderUpdated(orderId: $orderId) {
id
orderNumber
status
fulfillmentStatus
trackingInfo {
number
company
url
}
updatedAt
events {
type
message
createdAt
}
}
}
`;
// Real-time cart updates using subscription
const CartRealTime = ({ cartId }) => {
const { data, loading, error } = useSubscription(CART_UPDATED_SUBSCRIPTION, {
variables: { cartId }
});
const cart = data?.cartUpdated;
if (loading) return <p>Loading cart...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h3>Cart Total: ${cart?.totalAmount}</h3>
{cart?.appliedDiscounts?.map(discount => (
<div key={discount.code}>
<span>Discount: {discount.description} -${discount.amount}</span>
</div>
))}
</div>
);
};
const CART_UPDATED_SUBSCRIPTION = gql`
subscription CartUpdated($cartId: ID!) {
cartUpdated(cartId: $cartId) {
id
items {
id
product {
id
name
price
}
quantity
totalPrice
}
subtotal
totalAmount
appliedDiscounts {
code
amount
description
}
updatedAt
}
}
`;
// WebSocket subscription setup (Apollo Client 3)
import { WebSocketLink } from '@apollo/client/link/ws';
import { getMainDefinition } from '@apollo/client/utilities';
import { split, HttpLink } from '@apollo/client';
const wsLink = new WebSocketLink({
uri: 'wss://your-graphql-endpoint/graphql/subscriptions',
options: {
reconnect: true,
connectionParams: {
authToken: 'your-jwt-token',
},
},
});
const httpLink = new HttpLink({
uri: 'https://your-graphql-endpoint/graphql',
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink
);
const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
});
⚙️ API de E-commerce
🔴 complex
Design completo de API GraphQL para sistema de e-commerce
# E-commerce GraphQL API Schema
# ================================
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
# Custom scalars
scalar DateTime
scalar Decimal
scalar URL
scalar Email
scalar JSON
# Product types
type Product {
id: ID!
sku: String!
name: String!
description: String!
shortDescription: String
price: Decimal!
comparePrice: Decimal
costPrice: Decimal
weight: Float
dimensions: ProductDimensions
images: [ProductImage!]!
variants: [ProductVariant!]!
category: Category!
tags: [String!]!
status: ProductStatus!
featured: Boolean!
seo: ProductSEO
inventory: ProductInventory!
pricing: ProductPricing
reviews: ReviewConnection!
createdAt: DateTime!
updatedAt: DateTime!
publishedAt: DateTime
}
type ProductVariant {
id: ID!
sku: String!
title: String!
price: Decimal!
comparePrice: Decimal
weight: Float
inventoryQuantity: Int!
image: ProductImage
option1: String
option2: String
option3: String
selectedOptions: [SelectedOption!]!
}
type SelectedOption {
name: String!
value: String!
}
type ProductDimensions {
length: Float!
width: Float!
height: Float!
unit: DimensionUnit!
}
enum DimensionUnit {
CM
INCH
}
type ProductImage {
id: ID!
url: URL!
altText: String
position: Int!
isPrimary: Boolean!
width: Int
height: Int
}
type ProductSEO {
title: String
description: String
keywords: [String!]
slug: String
}
type ProductInventory {
quantity: Int!
reserved: Int!
available: Int!
trackQuantity: Boolean!
allowBackorder: Boolean!
lowStockThreshold: Int!
location: String
}
type ProductPricing {
basePrice: Decimal!
salePrice: Decimal
taxAmount: Decimal
taxIncluded: Boolean!
currency: String!
}
enum ProductStatus {
ACTIVE
DRAFT
ARCHIVED
OUT_OF_STOCK
}
# Category type
type Category {
id: ID!
name: String!
slug: String!
description: String
image: URL
parent: Category
children: [Category!]!
products(filter: ProductFilter, first: Int, after: String): ProductConnection!
productCount: Int!
seo: CategorySEO
}
type CategorySEO {
title: String
description: String
keywords: [String!]
}
# Customer types
type Customer {
id: ID!
email: Email!
firstName: String!
lastName: String!
phone: String
avatar: URL
birthday: DateTime
gender: Gender
addresses: [Address!]!
defaultAddress: Address
orders(filter: OrderFilter, first: Int, after: String): OrderConnection!
wishlist: [Product!]!
reviews: [Review!]!
stats: CustomerStats!
preferences: CustomerPreferences!
createdAt: DateTime!
updatedAt: DateTime!
}
enum Gender {
MALE
FEMALE
OTHER
PREFER_NOT_TO_SAY
}
type Address {
id: ID!
type: AddressType!
firstName: String!
lastName: String!
company: String
address1: String!
address2: String
city: String!
province: String!
country: String!
postalCode: String!
phone: String
isDefault: Boolean!
}
enum AddressType {
SHIPPING
BILLING
}
type CustomerStats {
totalOrders: Int!
totalSpent: Decimal!
averageOrderValue: Decimal!
lastOrderDate: DateTime
favoriteProducts: [Product!]!
orderFrequency: Float!
}
type CustomerPreferences {
language: String!
currency: String!
timezone: String!
marketingEmails: Boolean!
orderUpdates: Boolean!
recommendations: Boolean!
}
# Order types
type Order {
id: ID!
orderNumber: String!
customer: Customer!
status: OrderStatus!
financialStatus: FinancialStatus!
fulfillmentStatus: FulfillmentStatus!
currency: String!
subtotal: Decimal!
taxAmount: Decimal!
shippingAmount: Decimal!
discountAmount: Decimal!
totalAmount: Decimal!
items: [OrderItem!]!
shippingAddress: Address
billingAddress: Address
transactions: [Transaction!]!
fulfillments: [Fulfillment!]!
events: [OrderEvent!]!
notes: String
customerNotes: String
tags: [String!]!
createdAt: DateTime!
updatedAt: DateTime!
processedAt: DateTime
cancelledAt: DateTime
fulfilledAt: DateTime
}
type OrderItem {
id: ID!
product: Product!
variant: ProductVariant
quantity: Int!
unitPrice: Decimal!
totalPrice: Decimal!
discountAmount: Decimal
taxAmount: Decimal
customizations: [OrderItemCustomization!]!
}
type OrderItemCustomization {
name: String!
value: String!
price: Decimal!
}
enum OrderStatus {
PENDING
CONFIRMED
PROCESSING
SHIPPED
DELIVERED
CANCELLED
REFUNDED
}
enum FinancialStatus {
PENDING
AUTHORIZED
CAPTURED
PARTIALLY_REFUNDED
REFUNDED
VOIDED
}
enum FulfillmentStatus {
UNFULFILLED
PARTIAL
FULFILLED
}
type Transaction {
id: ID!
gateway: String!
gatewayTransactionId: String!
amount: Decimal!
currency: String!
status: TransactionStatus!
kind: TransactionKind!
errorCode: String
errorMessage: String
createdAt: DateTime!
processedAt: DateTime
}
enum TransactionStatus {
PENDING
SUCCESS
FAILURE
CANCELLED
}
enum TransactionKind {
AUTHORIZATION
CAPTURE
SALE
REFUND
VOID
type Fulfillment {
id: ID!
orderId: ID!
status: FulfillmentStatus!
trackingInfo: TrackingInfo
items: [FulfillmentItem!]!
createdAt: DateTime!
shippedAt: DateTime
deliveredAt: DateTime
}
type TrackingInfo {
company: String!
number: String!
url: URL
}
type FulfillmentItem {
id: ID!
orderItemId: ID!
quantity: Int!
}
type OrderEvent {
id: ID!
type: OrderEventType!
message: String!
metadata: JSON
createdAt: DateTime!
}
enum OrderEventType {
CREATED
UPDATED
CANCELLED
PAYMENT_RECEIVED
PAYMENT_FAILED
FULFILLMENT_CREATED
SHIPPED
DELIVERED
}
# Cart types
type Cart {
id: ID!
customer: Customer
items: [CartItem!]!
subtotal: Decimal!
taxAmount: Decimal!
shippingAmount: Decimal!
discountAmount: Decimal!
totalAmount: Decimal!
currency: String!
appliedDiscounts: [AppliedDiscount!]!
shippingAddress: Address
billingAddress: Address
createdAt: DateTime!
updatedAt: DateTime!
expiresAt: DateTime!
}
type CartItem {
id: ID!
product: Product!
variant: ProductVariant
quantity: Int!
unitPrice: Decimal!
totalPrice: Decimal!
customizations: [OrderItemCustomization!]!
}
type AppliedDiscount {
id: ID!
code: String!
amount: Decimal!
type: DiscountType!
description: String!
}
enum DiscountType {
PERCENTAGE
FIXED_AMOUNT
FREE_SHIPPING
}
# Review types
type Review {
id: ID!
product: Product!
customer: Customer!
rating: Int!
title: String
content: String!
images: [URL!]!
verified: Boolean!
helpful: Int!
createdAt: DateTime!
updatedAt: DateTime!
}
type ReviewConnection {
edges: [ReviewEdge!]!
pageInfo: PageInfo!
totalCount: Int!
averageRating: Float!
}
type ReviewEdge {
node: Review!
cursor: String!
}
# Input types
input ProductFilter {
category: ID
status: ProductStatus
featured: Boolean
priceMin: Decimal
priceMax: Decimal
search: String
tags: [String!]
inStock: Boolean
}
input CreateProductInput {
sku: String!
name: String!
description: String!
price: Decimal!
categoryId: ID!
images: [ProductImageInput!]!
variants: [ProductVariantInput!]
tags: [String!]
}
input ProductVariantInput {
sku: String!
title: String!
price: Decimal!
option1: String
option2: String
option3: String
inventoryQuantity: Int!
}
input ProductImageInput {
url: URL!
altText: String
position: Int
isPrimary: Boolean
}
input AddToCartInput {
productId: ID!
variantId: ID
quantity: Int!
customizations: [OrderItemCustomizationInput!]
}
input OrderItemCustomizationInput {
name: String!
value: String!
}
input CreateOrderInput {
cartId: ID!
shippingAddress: AddressInput!
billingAddress: AddressInput!
paymentMethod: PaymentMethodInput!
}
input AddressInput {
type: AddressType!
firstName: String!
lastName: String!
company: String
address1: String!
address2: String
city: String!
province: String!
country: String!
postalCode: String!
phone: String
}
input PaymentMethodInput {
gateway: String!
token: String!
savePaymentMethod: Boolean = false
}
# Query root
type Query {
# Product queries
product(id: ID!, slug: String): Product
products(filter: ProductFilter, first: Int, after: String, sort: ProductSort): ProductConnection!
featuredProducts(first: Int): [Product!]!
relatedProducts(productId: ID!, first: Int): [Product!]!
# Category queries
category(id: ID!, slug: String): Category
categories(parentId: ID): [Category!]!
# Customer queries
me: Customer
customer(id: ID!): Customer
# Order queries
order(id: ID!, orderNumber: String): Order
orders(filter: OrderFilter, first: Int, after: String): OrderConnection!
# Cart queries
cart(id: ID): Cart
activeCart: Cart
# Search
searchProducts(query: String!, first: Int, filter: ProductFilter): ProductConnection!
suggestions(query: String!, limit: Int): [String!]!
}
# Mutation root
type Mutation {
# Cart mutations
addToCart(input: AddToCartInput!): Cart!
updateCartItem(itemId: ID!, quantity: Int!): Cart!
removeFromCart(itemId: ID!): Cart!
clearCart: Cart!
applyDiscountCode(code: String!): Cart!
removeDiscountCode: Cart!
# Order mutations
createOrder(input: CreateOrderInput!): Order!
updateOrderAddress(orderId: ID!, shippingAddress: AddressInput, billingAddress: AddressInput): Order!
cancelOrder(orderId: ID!, reason: String): Order!
# Customer mutations
updateCustomer(input: UpdateCustomerInput!): Customer!
addAddress(input: AddressInput!): Customer!
updateAddress(id: ID!, input: AddressInput!): Customer!
removeAddress(id: ID!): Customer!
setDefaultAddress(id: ID!): Customer!
# Review mutations
createReview(productId: ID!, input: CreateReviewInput!): Review!
updateReview(id: ID!, input: UpdateReviewInput!): Review!
deleteReview(id: ID!): Boolean!
helpfulReview(reviewId: ID!): Boolean!
}
input CreateReviewInput {
rating: Int!
title: String
content: String!
images: [URL!]
}
input UpdateReviewInput {
rating: Int
title: String
content: String!
images: [URL!]
}
input UpdateCustomerInput {
firstName: String
lastName: String
phone: String
birthday: DateTime
gender: Gender
}
# Subscription root
type Subscription {
# Cart subscriptions
cartUpdated(cartId: ID!): Cart!
# Order subscriptions
orderUpdated(orderId: ID!): Order!
orderCreated(customerId: ID): Order!
# Product subscriptions
productUpdated(productId: ID!): Product!
lowStockAlert(productId: ID!): Product!
}
# Relay pagination types
type ProductConnection {
edges: [ProductEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type ProductEdge {
node: Product!
cursor: String!
}
type OrderConnection {
edges: [OrderEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type OrderEdge {
node: Order!
cursor: String!
}
# Sort enum
enum ProductSort {
CREATED_AT_ASC
CREATED_AT_DESC
NAME_ASC
NAME_DESC
PRICE_ASC
PRICE_DESC
RATING_DESC
BEST_SELLING
}
# Filter inputs
input OrderFilter {
status: OrderStatus
financialStatus: FinancialStatus
fulfillmentStatus: FulfillmentStatus
createdAfter: DateTime
createdBefore: DateTime
customerId: ID
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
⚙️ Recursos Avançados
🔴 complex
Recursos avançados do GraphQL e melhores práticas
# GraphQL Advanced Features and Best Practices
# ============================================
# Advanced query with directives, fragments, and aliases
query AdvancedProductSearch($filters: ProductFilter!, $userContext: UserContext) {
searchProducts(filter: $filters) {
products {
...productFields @include(if: $userContext.isLoggedIn)
...adminProductFields @include(if: $userContext.isAdmin)
price @client
inWishlist @client
discountPrice: price @client @export(as: "productPrice")
}
totalCount
facets {
name
values {
value
count
}
}
pageInfo {
hasNextPage
endCursor
}
}
wishlist @include(if: $userContext.isLoggedIn) {
items {
productId
addedAt
}
}
recommendations @skip(if: $userContext.hideRecommendations) {
id
name
price
rating
}
}
fragment productFields on Product {
id
name
description
images {
url
altText
isPrimary
}
category {
name
slug
}
variants {
id
title
price
inventoryQuantity
}
}
fragment adminProductFields on Product {
sku
costPrice
inventory {
quantity
reserved
location
}
salesData {
totalSold
revenue
lastSaleDate
}
}
# Custom scalar types with validation
scalar DateTime @specifiedBy(url: "https://scalars.graphql.org/koizam/date-time")
scalar Decimal @specifiedBy(url: "https://scalars.graphql.org/koizam/decimal")
scalar Email @specifiedBy(url: "https://scalars.graphql.org/koizam/email")
scalar URL @specifiedBy(url: "https://scalars.graphql.org/koizam/url")
scalar JSON
# Union types for polymorphic responses
union SearchableItem = Product | Article | User | Category
type SearchResult {
item: SearchableItem!
relevanceScore: Float!
highlights: [String!]!
}
query SearchEverything($query: String!, $types: [SearchableType!]) {
search(query: $query, types: $types) {
results {
item {
... on Product {
id
name
price
images {
url
}
}
... on Article {
id
title
excerpt
author {
name
}
}
... on User {
id
username
avatar
bio
}
... on Category {
id
name
productCount
image {
url
}
}
}
relevanceScore
highlights
}
totalCount
searchTime
}
}
# Interface types for shared fields
interface Node {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
}
interface Commentable {
id: ID!
comments(first: Int, after: String): CommentConnection!
totalComments: Int!
}
type Product implements Node & Commentable {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
comments(first: Int, after: String): CommentConnection!
totalComments: Int!
name: String!
price: Decimal!
}
type Article implements Node & Commentable {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
comments(first: Int, after: String): CommentConnection!
totalComments: Int!
title: String!
content: String!
}
# Advanced input types with validation rules
input AdvancedProductFilter {
category: ID @constraint(minLength: 1, maxLength: 50)
priceRange: PriceRangeInput
ratingRange: RatingRangeInput
tags: [String!] @constraint(maxItems: 10)
search: String @constraint(minLength: 2, maxLength: 100)
inStock: Boolean
featured: Boolean
customAttributes: [CustomAttributeInput!]
}
input PriceRangeInput {
min: Decimal @constraint(min: 0)
max: Decimal @constraint(min: 0)
}
input RatingRangeInput {
min: Float @constraint(min: 0, max: 5)
max: Float @constraint(min: 0, max: 5)
}
input CustomAttributeInput {
key: String! @constraint(minLength: 1, maxLength: 50)
value: String! @constraint(minLength: 1, maxLength: 200)
type: AttributeType!
}
enum AttributeType {
TEXT
NUMBER
BOOLEAN
DATE
}
# DataLoader integration for batch resolving
query BatchUserQueries($userIds: [ID!]!, $postIds: [ID!]!) {
users: usersByIds(ids: $userIds) {
id
username
email
profile {
avatar
bio
}
}
posts: postsByIds(ids: $postIds) {
id
title
content
author {
id
username
}
comments {
id
content
author {
id
username
}
}
}
}
# Caching directives
query CachedProductData($productId: ID!, $currency: String!) {
product(id: $productId) {
id
name
description @cache(ttl: 3600) # Cache for 1 hour
price(currency: $currency) @cache(ttl: 300) # Cache for 5 minutes
images @cache(ttl: 86400) # Cache for 24 hours
inventory {
quantity @cache(ttl: 60) # Cache for 1 minute
available
}
}
}
# Error handling with extensions
mutation ComplexOrderOperation($input: CreateOrderInput!) {
createOrder(input: $input) {
success
order {
id
orderNumber
status
totalAmount
}
errors {
field
message
code
extensions {
severity
retryable
additionalInfo
}
}
warnings {
message
code
}
}
}
# Rate limiting directives
query RateLimitedQueries($searchQuery: String!) {
searchProducts(query: $searchQuery)
@rateLimit(limit: 60, duration: "1m") # 60 requests per minute
{
products {
id
name
price
}
totalCount
}
advancedAnalytics(userId: "current")
@rateLimit(limit: 10, duration: "1m") # 10 requests per minute
{
purchaseHistory
recommendations
}
}
# Authentication and authorization directives
query SecureUserData($userId: ID!) {
user(id: $userId) @auth(required: true) {
id
email
profile {
personalInfo @auth(role: "admin") # Only admins can see personal info
financialData @auth(permission: "read_financial")
}
}
sensitiveOperations @auth(role: "admin") {
auditLogs
systemMetrics
}
}
# Complex mutations with validation
mutation ComplexProductCreation($input: ComplexProductInput!) {
createProduct(input: $input) {
product {
id
name
price
status
validationErrors {
field
message
severity
}
}
}
}
input ComplexProductInput {
# Basic info
name: String! @constraint(minLength: 1, maxLength: 200)
description: String @constraint(maxLength: 2000)
# Pricing
price: Decimal! @constraint(min: 0.01)
comparePrice: Decimal @constraint(min: 0)
# Inventory
inventory: InventoryInput!
# Media
images: [ProductImageInput!] @constraint(minItems: 1, maxItems: 10)
# Variants (optional)
variants: [ProductVariantInput!] @constraint(maxItems: 100)
# SEO
seo: SEOInput
# Advanced fields
customFields: JSON
webhooks: [WebhookInput!]
}
# Subscription filtering and permissions
subscription FilteredRealTimeUpdates(
$filter: RealTimeFilter!
$permissions: [String!]
) {
realTimeUpdates(filter: $filter)
@hasPermission(permissions: $permissions)
{
type
entity {
...on Product {
id
name
price
inventory
}
...on Order {
id
status
totalAmount
}
}
changes {
field
oldValue
newValue
}
timestamp
user {
id
username
}
}
}
# Federation for distributed schemas
# This would be in a product service
extend type Query {
product(id: ID!): Product
@requires(fields: "userId cartId")
productsByCategory(categoryId: ID!): [Product!]!
}
extend type User @key(fields: "id") {
id: ID! @external
preferences: UserPreferences @external
recentProducts: [Product!]!
}
# This would be in a user service
extend type User @key(fields: "id") {
id: ID! @external
preferences: UserPreferences @external
}
# Analytics tracking
query TrackedProductQueries($productId: ID!) {
product(id: $productId) {
id
name
price
views @track(metric: "product_views")
conversions @track(metric: "product_conversions")
}
relatedProducts(productId: $productId) {
id
name
price
}
recommendations(userId: "current")
@track(metric: "recommendations_shown")
{
id
name
score
reason
}
}
# Performance optimization with field selection
query OptimizedProductList($category: ID!, $fields: [String!]!) {
products(category: $category) {
id
... @include(if: $fields.contains("name")) {
name
}
... @include(if: $fields.contains("price")) {
price
}
... @include(if: $fields.contains("image")) {
image {
url
}
}
... @include(if: $fields.contains("description")) {
description
}
}
}
# Multi-tenant architecture
query MultiTenantQuery($tenantId: String!) {
tenantData(tenantId: $tenantId) {
products {
id
name
tenantPricing {
price
currency
discount
}
}
users {
id
email
tenantRole
}
settings {
theme
features
limits
}
}
}
# Schema stitching and delegation
extend type Query {
externalService: ExternalServiceQuery
@delegate(to: "external-service")
legacyData: LegacyDataQuery
@delegate(to: "legacy-system")
}
# GraphQL Playground introspection query
query IntrospectionQuery {
__schema {
types {
name
description
kind
fields {
name
type {
name
kind
}
}
}
queryType {
name
fields {
name
description
type {
name
}
args {
name
description
type {
name
}
}
}
}
}
}
# Advanced error handling and recovery
mutation ResilientOperation($input: ComplexInput!) {
resilientOperation(input: $input)
@retry(maxAttempts: 3, delay: 1000)
@circuitBreaker(errorThreshold: 5, timeout: 30000)
@timeout(milliseconds: 5000)
{
success
data
errors {
type
message
retryable
fallbackAvailable
}
}
}
# Custom directives definition (schema SDL)
directive @auth(required: Boolean = false, role: String, permission: String) on FIELD_DEFINITION | OBJECT
directive @cache(ttl: Int!) on FIELD
directive @rateLimit(limit: Int!, duration: String!) on FIELD
directive @constraint(minLength: Int, maxLength: Int, min: Float, max: Float, minItems: Int, maxItems: Int) on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
directive @hasPermission(permissions: [String!]!) on SUBSCRIPTION
directive @track(metric: String!) on FIELD
directive @include(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT
directive @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT
directive @export(as: String!) on FIELD
directive @client on FIELD
directive @requires(fields: String!) on OBJECT | FIELD_DEFINITION
directive @external on OBJECT | FIELD_DEFINITION
directive @key(fields: String!) on OBJECT
directive @delegate(to: String!) on FIELD
directive @retry(maxAttempts: Int!, delay: Int!) on FIELD
directive @circuitBreaker(errorThreshold: Int!, timeout: Int!) on FIELD
directive @timeout(milliseconds: Int!) on FIELD