WooCommerce REST API çalışır. GraphQL daha iyi çalışır — özellikle karmaşık, iç içe geçmiş ürün verilerini tek istekte getirmesi gereken frontend’ler için. WPGraphQL ve WooGraphQL eklentisi ile headless frontend’iniz tam olarak ihtiyacı olan veriyi isteyebilir, ne fazlası ne eksik.

Kurulum

WordPress backend’inizde iki eklenti kurun:

  • WPGraphQL — WordPress’e /graphql endpoint’i ekler
  • WooGraphQL — WPGraphQL’i WooCommerce türleri ve sorguları ile genişletir

GraphQL endpoint’iniz: https://your-store.com/graphql

WooCommerce için Neden REST Yerine GraphQL

Bir ürün listeleme sayfasını düşünün. REST ile şunlara ihtiyacınız var:

GET /wc/v3/products?per_page=12        → Ürünler (temel bilgi)

GET /wc/v3/products/categories → Tüm kategoriler (filtreler için)

GET /wc/v3/products/attributes → Tüm özellikler (filtreler için)

GET /wc/v3/products/{id}/variations → Varyasyonlar (ürün başına)

Bu 4+ API çağrısı, her biri ihtiyacınız olmayan veri döndürür. GraphQL ile:

query ProductListing($first: Int!, $after: String, $categoryIn: [Int]) {

products(first: $first, after: $after, where: { categoryIdIn: $categoryIn }) {

pageInfo {

hasNextPage

endCursor

}

nodes {

id

databaseId

name

slug

... on SimpleProduct {

price

regularPrice

salePrice

stockStatus

}

... on VariableProduct {

price

regularPrice

variations(first: 50) {

nodes {

databaseId

name

price

stockStatus

attributes {

nodes {

name

value

}

}

}

}

}

image {

sourceUrl(size: MEDIUM)

altText

}

productCategories {

nodes {

name

slug

}

}

}

}

}

Tek istek. Tam olarak ihtiyacınız olan alanlar. Aşırı veri getirme yok.

Temel Sorgular

Tekil Ürün

query GetProduct($slug: ID!) {

product(id: $slug, idType: SLUG) {

databaseId

name

slug

description

shortDescription

sku

... on SimpleProduct {

price

regularPrice

salePrice

stockQuantity

stockStatus

}

... on VariableProduct {

price

regularPrice

variations(first: 100) {

nodes {

databaseId

price

regularPrice

stockStatus

stockQuantity

attributes {

nodes { name value }

}

image {

sourceUrl(size: MEDIUM_LARGE)

altText

}

}

}

defaultAttributes {

nodes { name value }

}

}

galleryImages {

nodes {

sourceUrl(size: LARGE)

altText

}

}

productCategories {

nodes { name slug }

}

attributes {

nodes {

name

options

variation

}

}

related(first: 4) {

nodes {

name

slug

... on SimpleProduct { price }

image { sourceUrl(size: MEDIUM) }

}

}

}

}

Filtreli Ürün Arama

query SearchProducts(

$search: String,

$categoryIn: [Int],

$minPrice: Float,

$maxPrice: Float,

$orderBy: ProductsOrderByEnum,

$first: Int!

) {

products(

first: $first

where: {

search: $search

categoryIdIn: $categoryIn

minPrice: $minPrice

maxPrice: $maxPrice

orderby: { field: $orderBy, order: ASC }

}

) {

nodes {

databaseId

name

slug

... on SimpleProduct {

price

regularPrice

stockStatus

}

image {

sourceUrl(size: MEDIUM)

}

}

pageInfo {

total

hasNextPage

endCursor

}

}

}

Client Kurulumu (Next.js + Apollo)

// lib/apollo-client.js

import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';

const client = new ApolloClient({

link: new HttpLink({

uri: process.env.NEXT_PUBLIC_GRAPHQL_URL,

credentials: 'include'

}),

cache: new InMemoryCache({

typePolicies: {

Query: {

fields: {

products: {

keyArgs: ['where'],

merge(existing, incoming) {

return incoming; // Replace on new query

}

}

}

}

}

})

});

export default client;

// pages/products/[slug].js

import { gql } from '@apollo/client';

import client from '../../lib/apollo-client';

const GET_PRODUCT = gql...; // Query from above

export async function getStaticProps({ params }) {

const { data } = await client.query({

query: GET_PRODUCT,

variables: { slug: params.slug }

});

return {

props: { product: data.product },

revalidate: 300 // ISR: regenerate every 5 minutes

};

}

export async function getStaticPaths() {

const { data } = await client.query({

query: gql

query { products(first: 100) { nodes { slug } } }

});

return {

paths: data.products.nodes.map(p => ({ params: { slug: p.slug } })),

fallback: 'blocking'

};

}

Mutasyonlar: Sepet ve Ödeme

WooGraphQL sepet işlemleri için mutasyonlar sağlar:

mutation AddToCart($productId: Int!, $quantity: Int!) {

addToCart(input: { productId: $productId, quantity: $quantity }) {

cartItem {

key

product { node { name } }

quantity

total

}

cart {

total

subtotal

contentsCount

}

}

}

mutation Checkout($input: CheckoutInput!) {

checkout(input: $input) {

order {

databaseId

orderNumber

status

total

}

result

}

}

Performans İpuçları

  • Kalıcı sorgular: Payload boyutunu azaltmak ve rastgele sorguları önlemek için sorgularınızı sunucuda önceden kaydedin
  • Sorgu karmaşıklık limitleri: Pahalı iç içe sorguları önlemek için graphql_max_query_depth ayarlayın
  • DataLoader deseni: WPGraphQL dahili olarak DataLoader kullanır, özel resolver’lar da kullanmalıdır
  • Fragment yeniden kullanımı: Ürün kartı fragment’leri tanımlayın ve sorgular arasında yeniden kullanın
  • Statik oluşturma: Ürün sayfaları için client-side sorgular yerine ISR ile getStaticProps kullanın

fragment ProductCard on Product {

databaseId

name

slug

... on SimpleProduct { price salePrice stockStatus }

... on VariableProduct { price }

image { sourceUrl(size: MEDIUM) altText }

}

query LatestProducts {

products(first: 8, where: { orderby: { field: DATE } }) {

nodes { ...ProductCard }

}

}

GraphQL vs REST: Hangisini Ne Zaman Kullanmalı

Senaryo Önerilen Neden
Ürün listeleri (karmaşık) GraphQL Daha az istek, tam alanlar
Sepet işlemleri REST (Store API) Daha iyi oturum yönetimi
Basit CRUD REST Daha basit uygulama
Mobil uygulamalar GraphQL Bant genişliği verimliliği
Sunucu tarafı rendering GraphQL Sayfa başına tek istek
Webhook’lar REST GraphQL push desteklemez

Sonuç

WPGraphQL + WooGraphQL, frontend’iniz karmaşık, iç içe geçmiş ürün verilerine ihtiyaç duyduğunda headless WooCommerce için optimal veri katmanıdır. Öğrenme eğrisi REST’ten daha dikken, elde edilen faydalar — daha az istek, tam veri getirme ve tür güvenliği — üretim headless mağazaları için yatırımı değerli kılar. En iyi sonucu almak için okuma işlemleri (ürünler, kategoriler, içerik) için GraphQL ve yazma işlemleri (sepet, ödeme, siparişler) için REST kullanın.

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

Close Search Window