2023-08-05 20:17:08+00:00

Building modern, responsive e-commerce storefronts requires high flexibility at the frontend layer. The checkout interface needs to fetch cart items, recalculate shipping methods, adjust taxes, and update promo codes dynamically. While traditional REST APIs require multiple round-trips to do this, GraphQL allows you to query all this data in a single request.

Using Django as the backend (with graphene-django) and Angular at the frontend (with Apollo Client), we design type-safe GraphQL schemas that simplify our state management.


1. Designing the Order Schema in Django

We define GraphQL types and mutations using Graphene-Django to structure orders, line items, and addresses:

# GraphQL Order Query in Django Graphene
import graphene
from graphene_django import DjangoObjectType
from order.models import Order

class OrderType(DjangoObjectType):
    class Meta:
        model = Order
        fields = ("id", "total", "state", "lines", "shipping_address")

class Query(graphene.ObjectType):
    active_order = graphene.Field(OrderType, cart_id=graphene.String())

    def resolve_active_order(self, info, cart_id=None):
        return Order.objects.filter(cart__id=cart_id, state="CART").first()

2. Requesting Data in Angular

On the Angular frontend, we construct queries that fetch precisely the fields needed for the active view, avoiding over-fetching and keeping mobile page load speeds high. The frontend can query order subTotals, shipping method availability, and billing states in one payload.