0
votes

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.

1
Follow up question? Is there a better way to chain such mutations? From the front end UI, I want to be able to make one call to graphql apollo server that will make 2 API calls, one for creating a contact and another for creating an address. The address will need the contactID that is created. - Chris Fricke

1 Answers

1
votes

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 };
      }
    },
  }