Relational mutations in Graphql Amplify

2

I have the following Graphql schema with relationship:

type Product @model{
  id: ID! @primaryKey
  name: String!
  img: String!
  components: [Component]! @hasMany
  categories: [Category]! @hasMany
}
type Component @model{
  id: ID! @primaryKey
  name: String!
}
type Category @model{
  id: ID! @primaryKey
  name: String!
}

A product can have multiple components and multiple categories.

I would like to have a mutations that can allow me to create a Product and also the components and categories associated.

Amplify codegen already created the mutation "CreateProduct" but it don't allow me to specify the component and category data in order to create them and link to the product.

It seems that i must create the product first and then the component and category separately.

I need to write a custom mutation in order to do what i want or it's impossible?

If it's possible with a custom mutation, how can I write it?

Thank you!

  • I have the same problem, I would like to populate all tables starting from a complete json object. I am wondering if there is a way to accomplish this

1개 답변
1

Hi!

Assuming you want to:

  • Create a new Component (not already persisted on your datasource)
  • Create a new Category (not already persisted on your datasource)
  • Create a new Product

You could execute multiple mutation in this way:

mutation CreateProductAndComponentsAndCategories(...){
  product: createProduct(input: {...}){
    id
  }
  # Create product's component
  firstComponent: createComponent(input: {...}){
    id
  }   
  # Create product's component
  secondComponent: createComponent(input: {...}){
    id
  }   
  # Create product's category
  firstCategory: createCategory...
}

If instead you intended to call the mutation createProduct and also providing a list of components and categories I think it is not possible.

This is because a mutation can be connected to a single DataSource and in your case the models should have 3 different DS:

  1. Product -> ProductDS
  2. Component -> ComponentDS
  3. Category -> CategoryDS

For the same reason, even creating a custom mutation mapping template would not solve the problem.

Try taking a look at Pipeline Resolvers. You should be able to create a pipeline that takes Product, Components and Categories as input which in turn calls 3 distinct functions.

Hypothetically:

  1. Function 1: create the components
  2. Function 2: create categories
  3. Function 3: creates the product by associating the keys of the components and categories of functions 1 and 2

I've never tried pipelined mutations, but theoretically they should work! :-)

답변함 2년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠