Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL: best way to manage mutations with interfaces?

I'am new to GraphQL but I really like it. Now that I'am playing with interfaces and unions, I'am facing a problem with mutations.

Suppose that I have this schema :

interface FoodType {
  id: String
  type: String
}

type Pizza implements FoodType {
  id: String
  type: String
  pizzaType: String
  toppings: [String]
  size: String
}

type Salad implements FoodType {
  id: String
  type: String
  vegetarian: Boolean
  dressing: Boolean
}

type BasicFood implements FoodType {
  id: String
  type: String
}

Now, I'd like to create new food items, so I started doing something like this :

type Mutation {
    addPizza(input:Pizza):FoodType
    addSalad(input:Salad):FoodType
    addBasic(input:BasicFood):FoodType
}

This did not work for 2 reasons :

  1. If I want to pass an object as parameter, this one must be an "input" type. But "Pizza", "Salad" and "BasicFood" are just "type".
  2. An input type cannot implement an interface.

So, my question is : How do you work with mutations in this context of interface without having to duplicate types too much? I'd like to avoid having a Pizza type for queries and an InputPizza type for mutations.

Thank you for your help.

like image 716
Fred Mériot Avatar asked Oct 28 '22 20:10

Fred Mériot


1 Answers

Input and Output types are fundamentally different things, just because you may have ones that happen to represent a similar object (eg Pizza and PizzaInput), it's a false equivalence.

Let's say in your schema Pizza has a mandatory id field (your IDs aren't mandatory, but probably should be). It probably wouldn't make sense for PizzaInput to have an ID field -- it would be generated by the server. The point i'm making is that in anything but the simplest systems, there's going to be processing to turn user input into a fully-fledged object to return.

You just have to bite the bullet and do what feels like duplicated work, you'll see the benefits in the long run.

like image 112
Andrew Ingram Avatar answered Nov 15 '22 09:11

Andrew Ingram