Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graphql with nested mutations?

I am trying to figure out how to mutate a nested object with graphql mutations, if possible. For instance I have the following schema:

type Event {
    id: String
    name: String
    description: String
    place: Place
}

type Place {
    id: String
    name: String
    location: Location
}

type Location {
    city: String
    country: String
    zip: String
}

type Query {
    events: [Event]
}

type Mutation {
    updateEvent(id: String, name: String, description: String): Event
}

schema {
    query: Query
    mutation: Mutation
}

How can I add the place information inside my updateEvent mutation?

like image 406
jsan Avatar asked Mar 08 '17 11:03

jsan


1 Answers

Generally speaking, you should avoid thinking of the arguments to your mutations as a direct mapping to object types in your schema. Whilst it's true that they will often be similar, you're better off approaching things under the assumption that they won't be.

Using your basic types as an example. Let's say I wanted to create a new event, but rather than knowing the location, I just have the longitude/latitude - it's actually the backend that calculates the real location object from this data, and I certainly don't know its ID (it doesn't have one yet!). I'd probably construct my mutation like this:

input Point {
  longitude: Float!
  latitude: Float!
}

input PlaceInput {
  name
  coordinates: Point!
}

type mutation {
  createEvent(
    name: String!
    description: String
    placeId: ID
    newPlace: PlaceInput
  ): Event  
  updateEvent(
    id: ID!
    name: String!
    description: String
    placeId: ID
    newPlace: PlaceInput
  ): Event
)

A mutation is basically just a function call, and it's best to think of it in those terms. If you wrote a function to create an Event, you likely wouldn't provide it an event and expect it to return an event, you'd provide the information necessary to create an Event.

like image 72
Andrew Ingram Avatar answered Sep 22 '22 14:09

Andrew Ingram