Graphql with nested mutations?

白昼怎懂夜的黑 提交于 2019-12-10 10:55: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 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
}
`



回答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.



来源:https://stackoverflow.com/questions/42670733/graphql-with-nested-mutations

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