javascriptgraphqlprisma-graphqlnexus-prisma

Nexus-prisma: order nested connections


What is the best way to keep order of nested objects in the schema.

My schema:

type Article {
  id: ID! @id
  pages: [Page!]!
}

type Page {
  id: ID! @id
}

This is how I'm trying to sort the pages(unsuccessfully):

  updateArticle({
    variables: {
      aricle.id,
      data: {
        pages: {
          connect: reorderPages(aricle.pages)
        }
      }
    }

The resolver:

 t.field("updateArticle", {
      type: "Article",
      args: {
        id: idArg(),
        data: t.prismaType.updateArticle.args.data
      },
      resolve: (_, { id, data }) => {
        return ctx.prisma.updateArticle({
          where: { id },
          data
        });
      }
    });

I understand why this approach is wrong. I guess that the order should be written in the database by an order index in the connection table. I don't know how to process that by GraphQL/Nexus/Prisma/MySQL.


Solution

  • For N:M to relations the schema would look like this:

    type Article {
      id: ID! @id
      title: String!
      items: [ArticleItemEdge!]! 
    }
    
    type ArticleItemEdge {
      id: ID! @id
      article: Article! @relation(link: INLINE)
      item: Item! @relation(link: INLINE)
      order: Int!
    }
    
    type Item {
      id: ID! @id
      title: String!
      articles: [ArticleItemEdge!]!
    }
    

    And then query articles in a more "Relay" like fashion with edges & nodes

    query {
      articles {
        items(orderBy: order_ASC) {
          item {
            title
          }
        }
      }
    }
    

    And if N:M isn't needed, you can update the schema definition like so:

    type Article {
      id: ID! @id
      items: [Item!]!
    }
    
    type Item {
      id: ID! @id
      article: Article! @relation(link: INLINE)
      order: Int!
    }
    

    ^ this will turn the db tables into 1:N relation ship rather than n:m

    Then you can issue a query like so:

    query {
      articles {
        id
        items(orderBy: order_ASC) {
          id
        }
      }
    }
    

    Updating the value of the "order" should be straight forward so I'll omit it here.

    Hope it answers your question!