Graphql with nested mutations?

2019-06-05 21:08发布

问题:

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?

回答1:

If you want to add a whole object to the mutation you have to define a graphql element of the type input. Here is a link to a small cheatsheet.

In your case it could look like this:

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

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

input PlaceInput {
    id: ID!
    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, place: PlaceInput!): Event
}

schema {
    query: Query
    mutation: Mutation
}
`



回答2:

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.