Sharing data between @QueryMapping and @SchemaMapping in Java Spring GraphQL

Sharing data between @QueryMapping and @SchemaMapping in Java Spring GraphQL


3

I have a schema defined as follows:

enum CardType {
    TYPE_1
    TYPE_2
}

type Card {
    id: ID!
}

type Order {
    id: ID!
    cards: [Card]!
}

input OrderFilter {
    cardType: CardType
}

type Query {
    getOrders(orderFilter: OrderFilter): [Order]
}

Also, the following resolvers:

@QueryMapping
public List<Order> getOrders(@Argument OrderFilter orderFilter) {
    return this.orderService.get(orderFilter);
}

@SchemaMapping
public List<Card> cards(Order order) {
    return this.cardService.getCards(order);
}

Is there a way for me to gain access to the OrderFilter argument from the @SchemaMapping annotated method? I want to filter the result from that method based on the argument of the @QueryMapping annotated method.

I tried to add an @Argument annotated parameter in the @SchemaMapping annotated method, but it does not work.

Share

1

  • I've been looking for this too but can't find anything. Maybe you could add an orderfilter into the order or cards list into the order. Kind of stinky though haha

    – brando f

    Apr 3 at 16:21

2 Answers
2

Reset to default


0

I looked through the GraphQl docs for a while and didn’t find anything.

My best solution was to make a "OrderGraphqlDTO" object that extended the "Order" object. Then I put a "OrderFilter" as a field in that. I excluded that field from the graphql schema so that it still only returned what looked like our order object, but now the OrderFilter was accessable in the "cards" method.

Not the best way since I couldn’t find in graphql support for this situation. At least it looked a little more elegant though.

Here’s the code:

public class OrderGraphqlDTO extends Order
{
    private OrderFilter orderFilter;
   
    ...
}
@QueryMapping
public List<OrderGraphqlDTO> getOrders(@Argument OrderFilter orderFilter) {
    Order order = this.orderService.get(orderFilter);
    return new OrderGraphqlDTO(order, orderFilter);
}

@SchemaMapping
public List<Card> cards(Order order) {
    OrderGraphqlDTO orderQl = (OrderGraphqlDTO) order;
    return this.cardService.getCards(orderQl);
}

Share


0

DataFetchingEnvironment class can be used to read the filter values.

@SchemaMapping
public List<Card> cards(DataFetchingEnvironment environment, Order order..) {
  //your code here
  ...environment.getVariables().get("orderFilter")
  //your code here
  return this.cardService.getCards(order);
}

Share



Not the answer you're looking for? Browse other questions tagged

or ask your own question.

Leave a Reply

Your email address will not be published. Required fields are marked *