Apollo / React mutating two related tables

Let's say I have two tables, one containing products and the other containing prices.

In Graphql, a query might look like this:

option {
    id
    price {
      id
      optionID
      price
      date
    }
    description
}

      

I present to the user one form (in reagent) where they can enter the details and the price of the product at the same time.

When they submit the form, I need to create a record in the "product" table and then create a corresponding record in the "price" table.

I am very new to Graphql and this is real and I find it a steep learning curve and follow the Apollo tutorial and docs reading, but the solution is still a mystery!

Can someone take me out of my misery and give me, or point me aside, the simplest example of handling the mutations needed to do this?

+3


source to share


1 answer


In short, something that actually needs to be handled by your server if you want to optimize as few requests as possible.

Problem: The problem is that you have an addiction. First you need to create a product and then a product ID, associate it with a new price.

Decision. ... The best way to implement this on the server is to add another field to the product in your mutation input, which allows you to enter details for Price, as well as in the same input prompt. This is called "nested creation" in Scaphold.

For example:



// Mutation
mutation CreateProduct ($input: CreateProductInput!) {
  createProduct(input: $input) {
    changedProduct {
      id
      name
      price {
        id
        amount
      }
    }
  }
}

// Variables
{
  input: {
    name: "My First Product",
    price: {
      amount: 1000
    }
  }
}

      

Then on the server you can parse the price object in your resolver arguments and create a new price object when you create the product. Meanwhile, you can also link them in one pass on the server.

Hope this helps!

+2


source







All Articles