15

I'm trying to implement GraphQL mutation for a "complex" object. Let's say we have a Contact with three fields: firstName, lastName and address, which is object with one field street:

Here is my python scheme implementation:

class Address(graphene.ObjectType):
    street = graphene.String(description='Street Name')


class AddressInput(graphene.InputObjectType):
    street = graphene.String(description='Street Name', required=True)


class Contact(graphene.ObjectType):
    first_name = graphene.String(description='First Name')
    last_name = graphene.String(description='Last Name')
    address = graphene.Field(Address, description='Contact address')


class ContactInput(graphene.InputObjectType):
    first_name = graphene.String(description='First Name', required=True)
    last_name = graphene.String(description='Last Name', required=True)
    address = AddressInput(description='Contact address', required=True)


class CreateContact(graphene.Mutation):
    class Input:
        contact = ContactInput()

    contact = graphene.Field(Contact, description='Created Contact object')

    @staticmethod
    def mutate(instance, args, context, info):
        contact = Contact(**args['contact'])
        return CreateContact(contact=contact)

and when I run this query:

mutation CreateContact($contact: ContactInput!) {
    createContact(contact: $contact) {
        contact {
            firstName
            address {
                street
            }
        }
    }
}

with the following variables:

{
    "contact": {
        "address": {
            "street": "Bond Blvd"
        },
        "firstName": "John",
        "lastName": "Doe"
    }
}

I get the following result:

{
    "createContact": {
        "contact": {
            "address": {
                "street": null
            },
            "firstName": "John"
        }
    }
}

As you can see, street field is null in results.

I can get what I need if I change mutate method to be like:

@staticmethod
def mutate(instance, args, context, info):
    args['contact']['address'] = Address(**args['contact']['address'])
    contact = Contact(**args['contact'])
    return CreateContact(contact=contact)

But I'm not sure this is a proper way.

So please advise a correct way to initiate nested structures.

sazzy4o
  • 3,073
  • 6
  • 34
  • 62
Pavel Reznikov
  • 2,968
  • 1
  • 18
  • 17

0 Answers0