Nexus-prisma: order nested connections
Asked Answered
R

1

7

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.

Richter answered 27/5, 2019 at 8:25 Comment(2)
Why are you not using the orderBy argument?Beatrix
So do you please mean to update all the nested object with an order index and then sort them by orderBy?Richter
K
2

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!

Koval answered 7/6, 2019 at 9:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.