Chris Fricke
Chris Fricke

Reputation: 65

Apollo GraphQL Nested Mutation

need some help on nested mutations.

Abstracted scenario is this:

I want to combine 2 mutation calls on apollo-server to first create a a Customer then create an Address for that customer. The Address mutation needs a customerID to be able to do this but also has information from the original overall mutation that it needs access to.

Here's the generic code:

makeExecutableSchema({
  typeDefs: gql`
    type Mutation {
      createCustomerWithAddress(customer: CustomerRequest!, address: AddressRequest!): Response
    }
    input CustomerRequest {
       name: String!
    }

    input AddressRequest {
       address: String!
       city: String!
       state: String!
       country: String!
    }

    type Response {
       customerID: Int!
       addressID: Int!
    }
  `,
  resolvers: {
    Mutation: {
      createCustomerWithAddress: async (_, {customer}, context, info) => {
        return await api.someAsyncCall(customer);
      }
    },
    Response: {
      addressID: async(customerID) => {
        // how do we get AddressRequest here?
        return await api.someAsyncCall(customerID, address);
      }
    }
  }
})



There's a lot of complexity I'm not showing from the original code, but what I wanted to get at is just at the root of how to access request params via sub mutations, if even possible. I don't really want to pass down address from the top mutation to the sub mutation.

Upvotes: 2

Views: 2452

Answers (1)

SILENT
SILENT

Reputation: 4258

You don't need a Response field in resolvers. createCustomerWithAddress should return an object shaped like Response.

resolvers: {
    Mutation: {
      createCustomerWithAddress: async (_, {customer, address}, context, info) => {
        // create customer
        const customerId = await api.CreateCustomer(customer);
        // create address and assign customerId
        const addressId = await api.CreateAddress({ ...address, customerId });
        // return response
        return { customerId, addressId };
      }
    },
  }

Upvotes: 1

Related Questions