graphql-python / swapi-graphene

GraphQL Starwars API using Graphene and Django

Home Page:http://swapi.graphene-python.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Mutation example (#2) doesn't work

mhmmdd opened this issue · comments

This useful example now doesn't work, can you update?

mutation MyMutation {
  createHero(input:{clientMutationId:"a", name:"Peter", homeworldId:"1"}) {
    hero {
      id
      name
      homeworld {
        id
        name
      }
    }
    ok
  }
}

@mhmmdd same for me here !! 😞

@mhmmdd the problem was in the implementation of the mutation. I think that the Star Wars example was using the old way to do mutation.

Original Code

class CreateHero(graphene.ClientIDMutation):

    class Input:
        name = graphene.String(required=True)
        homeworld_id = graphene.String(required=True)

    hero = graphene.Field(Hero)
    ok = graphene.Boolean()

    @classmethod
    def mutate_and_get_payload(cls, input, info):
        name = input.get('name')
        homeworld_id = input.get('homeworld_id')
        try:
            homeworld_id = int(homeworld_id)
        except ValueError:
            try:
                _type, homeworld_id = Node.from_global_id(homeworld_id)
                assert _type == 'planet', 'The homeworld should be a Planet, but found {}'.format(resolved.type)
            except:
                raise Exception("Received wrong Planet id: {}".format(homeworld_id))

        homeworld = Planet._meta.model.objects.get(id=homeworld_id)
        hero = Hero._meta.model(name=name, homeworld=homeworld)
        hero.save()

        return CreateHero(hero=hero, ok=bool(hero.id))


class Mutation(graphene.ObjectType):
    create_hero = graphene.Field(CreateHero)

The modified version

class CreateHero(graphene.Mutation):

    class Input:
        name = graphene.String(required=True)
        homeworld_id = graphene.String(required=True)

    hero = graphene.Field(Hero)
    ok = graphene.Boolean()

    def mutate(self, args, context, info):
        print "Mutate------------------"
        name = args.get('name')
        homeworld_id = args.get('homeworld_id')
        try:
            homeworld_id = int(homeworld_id)
        except ValueError:
            try:
                _type, homeworld_id = Node.from_global_id(homeworld_id)
                assert _type == 'planet', 'The homeworld should be a Planet, but found {}'.format(resolved.type)
            except:
                raise Exception("Received wrong Planet id: {}".format(homeworld_id))

        homeworld = Planet._meta.model.objects.get(id=homeworld_id)
        hero = Hero._meta.model(name=name, homeworld=homeworld)
        hero.save()

        return CreateHero(hero=hero, ok=bool(hero.id))


class Mutation(graphene.ObjectType):
    create_hero = CreateHero.Field()

Fixed in master. Closing issue