Recommended way to batch create nested self-referencing types

prisma

#1

I was wondering what the recommended strategy would be to create a mutation with nested types.

In a simplified example I have following types of an Article that has many Sections which can have many SubSections:

type Article {
  id: ID! @unique
  name: String
  sections: [Section!]!
}

type Section {
  id: ID! @unique
  name: String
  sections: [Section!]! @relation(name:"Sections")
}

and in my Apollo Gateway I’d like to use prisma-client with the generated mutation resolver to create a deeply nested structure like following:

export const Mutation: MutationResolvers.Type = {
  ...MutationResolvers.defaultResolvers,

  createArticle: (parent, args, ctx) => {
    return ctx.prisma.createArticle({
      name: 'My Article',
      sections: {
        create: {
          name: 'My first section',
          sections: {
            create: {
              name: 'My subsection'
              // and my sub-subsections are missing...
            }
          }
        }
      }
    });
  }
};

I understand that prisma generates in the create a SectionCreateManyWithoutSectionsInput that, as the name indicates doesn’t include the list of sections allowing recursion.

The two strategies I could think of so far would be to create a custom input type that can be nested as deeply as necessary and then in the Gateway separate it to

  1. use a series of create and connect calls to end up with the desired output.
  2. create manually a nested mutation to be directly executed via ctx.prisma.$graphql(...)

Would there be a more efficient way to create nested mutations?

The mutation I’d like to replicate with prisma-client is following:

mutation nested {
  createArticle(
    data: {
      name: "My Article"
      sections: {
        create: {
          name: "My first section"
          sections: {
            create: {
              name: "My subsection"
              sections: {
                create: {
                  name: "My subsubsection"
                  # ...
                }
              }
            }
          }
        }
      }
    }
  ) {
    id
    name
    sections {
      id
      name
      sections {
        id
        name
        sections {
          id
          name
          sections {
            id
            name
          }
        }
      }
    }
  }
}

#2

Hi @alx-andru

Yes, you will need to use $graphql for this. We do not generate this on the js client as to ensure type safety


#3

Hi @pantharshit00,

thanks for the response. I thought it might be the case but was hoping there would be a better way to do it ensuring type safety.


#4

This topic was automatically closed 45 days after the last reply. New replies are no longer allowed.