Problem
You need to add a new for a GraphQL query in Saleor but don´t know how.
Solution
Adding a new resolver in Saleor is not difficult. Let me walk you through the steps for order_by_checkout_token:
- Add resolver function to saleor/graphql/$area.py (in our example $area = order, so saleor/graphql/order.py)
- Add import from saleor/graphql/$area.py (in our example $area = order, so saleor/graphql/order.py)
- Add to saleor/graphql/$area/schema.py (in our example $area = order, so saleor/graphql/order/schema.py) schema defintion
- Add to saleor/graphql/$area/schema.py (in our example $area = order, so saleor/graphql/order/schema.py) class $areaQuery defintion
Step 1: Implement resolver Function
Implement the resolver function in the corresponding area (saleor/graphql/$area.py), in this case saleor/graphql/order.py.
This function receives the token from the checkout ( a string) to be used as a filter.
It excludes the DRAFT Status Orders as they were not relevant for the task at hand. Then it filters by the supplied token and returns the first entry (no need to handle array stuff)
def resolve_order_by_checkout_token(token):
return (
models.Order.objects.exclude(status=OrderStatus.DRAFT)
.filter(checkout_token=token)
.first()
)
Step 2: Import the resolver
Import the resolver function in the corresponding Area of the GraphQL Schema handler (saleor/graphql/$area.py), here saleor/graphql/order.py
To do that search for
from .resolvers import (
and add
resolve_order_by_checkout_token
to the list
Step 3: Add to the Schema definition
It´s basically adding a method to the class, that holds contextual information and calls your resolver function.
To do that add to saleor/graphql/order/schema.py, like this:
def resolve_order_by_checkout_token(self, _info, token):
return resolve_order_by_checkout_token(token)
Step 4: Add to $areaQueries Class definition
The last step is making the Query know to the $areaQueries class, in this case OrderQueries. This is also inside the schema.py from Step 3.
In this case it looks like this:
order_by_checkout_token = graphene.Field(
Order,
description=”Look up an order by token.”,
checkout_token=graphene.Argument(
graphene.UUID, description=”The order’s token.”, required=True
),
)
Summary
You learned how to add a resolver for the query OrderByCheckoutToken, which allows you based on Checkout Token to receive the Order Entry from the Database.
I had to use it on the Saleor Storefront to handle a few things that are different based on the 3DS payment process with redirects.
Let me know when it helped you.
Best,
Frank
Sources: