Проблема с RANGE_ADD в Relay Mutations

Я просматривал документы реле и пришел к следующему коду в RANGE_ADD.

class IntroduceShipMutation extends Relay.Mutation {
  // This mutation declares a dependency on the faction
  // into which this ship is to be introduced.
  static fragments = {
    faction: () => Relay.QL`fragment on Faction { id }`,
  };
  // Introducing a ship will add it to a faction's fleet, so we
  // specify the faction's ships connection as part of the fat query.
  getFatQuery() {
    return Relay.QL`
      fragment on IntroduceShipPayload {
        faction { ships },
        newShipEdge,
      }
    `;
  }
  getConfigs() {
    return [{
      type: 'RANGE_ADD',
      parentName: 'faction',
      parentID: this.props.faction.id,
      connectionName: 'ships',
      edgeName: 'newShipEdge',  
      rangeBehaviors: {
        // When the ships connection is not under the influence
        // of any call, append the ship to the end of the connection
        '': 'append',
        // Prepend the ship, wherever the connection is sorted by age
        'orderby(newest)': 'prepend',
      },
    }];
  }
  /* ... */
}

Здесь упоминается, что edgeName требуется для добавления нового узла к соединению. Выглядит хорошо и нормально.

Теперь я продвинулся дальше по документации и дошел до GraphQL реализации этой мутации.

mutation AddBWingQuery($input: IntroduceShipInput!) {
  introduceShip(input: $input) {
    ship {
      id
      name
    }
    faction {
      name
    }
    clientMutationId
  }
}

Теперь, согласно документам, эта мутация дает мне вывод как

{
  "introduceShip": {
    "ship": {
      "id": "U2hpcDo5",
      "name": "B-Wing"
    },
    "faction": {
      "name": "Alliance to Restore the Republic"
    },
    "clientMutationId": "abcde"
  }
}

Я не вижу присутствия edgeName здесь.

В своем проекте я использовал графен. Там я тоже видел нечто подобное, только

class IntroduceShip(relay.ClientIDMutation):
  class Input:
    ship_name = graphene.String(required=True)
    faction_id = graphene.String(required=True)

ship = graphene.Field(Ship)
faction = graphene.Field(Faction)

@classmethod
def mutate_and_get_payload(cls, input, context, info):
    ship_name = input.get('ship_name')
    faction_id = input.get('faction_id')
    ship = create_ship(ship_name, faction_id)
    faction = get_faction(faction_id)
    return IntroduceShip(ship=ship, faction=faction)

Здесь я тоже нигде не вижу edgeName.

Любая помощь, пожалуйста? Я работаю над мутациями в первую очередь, поэтому хотел подтвердить, что я что-то упускаю или здесь что-то не так?


person Harkirat Saluja    schedule 09.02.2017    source источник


Ответы (1)


Этот пример можно либо упростить, либо немного упростить, потому что на практике необходимо возвращать край, и это именно то, что извлекается реле (другие поля в RANGE_ADD являются скорее своего рода декларацией и не обязательно доставлено).

Вот как это можно сделать в графене:

# Import valid as of graphene==0.10.2 and graphql-relay=0.4.4
from graphql_relay.connection.arrayconnection import offset_to_cursor

class IntroduceShip(relay.ClientIDMutation):
    class Input:
        ship_name = graphene.String(required=True)
        faction_id = graphene.String(required=True)

    ship = graphene.Field(Ship)
    faction = graphene.Field(Faction)
    new_ship_edge = graphene.Field(Ship.get_edge_type().for_node(Ship))

    @classmethod
    def mutate_and_get_payload(cls, input, context, info):
        ship_name = input.get('ship_name')
        faction_id = input.get('faction_id')
        ship = create_ship(ship_name, faction_id)
        faction = get_faction(faction_id)

        ship_edge_type = Ship.get_edge_type().for_node(Ship)
        new_ship_edge = edge_type(
            # Assuming get_ships_number supplied
            cursor=offset_to_cursor(get_ships_number())
            node=ship
        )

        return cls(ship=ship, faction=faction, new_ship_edge=new_ship_edge)
person glowka    schedule 09.02.2017