Graphql with nested mutations?

最后都变了- 提交于 2019-12-06 04:08:08

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 Location {
    city: String
    country: String
    zip: String
}

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

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

input LocationInput {
   city: String
   country: String
   zip: String
}

input PlaceInput {
    id: ID!
    name: String!
    location: LocationInput!
}

type Query {
    events: [Event]
}

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

schema {
    query: Query
    mutation: Mutation
}
`

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!