graphql-js icon indicating copy to clipboard operation
graphql-js copied to clipboard

graphql resolver circular dependency type error (bi-directional relation)

Open catinrage opened this issue 1 year ago • 1 comments

Questions regarding how to use GraphQL

given this schema :

type Query {
  getUser(id: ID!): User
}

type User {
  id: ID!
  username: String!
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  user: User!
}

when i try to create the resolvers for this (i use prisma as datasource and codegen for type generation) i always get type error because User needs the field posts to be present and also Post need the field user, and this causes a circular dependency i can not handle.

my resolver looks something like this :

const resolvers = {
  Query: {
    getUser: async (parent, { id }, { prisma }) => {
      return await prisma.user.findUnique({
        where: {
          id,
        },
        include: {
          posts: true,
        },
      });
    },
  },
  User: {
    posts: async (parent, _, { prisma }) => {
      return await prisma.post.findMany({
        where: {
          userId: parent.id,
        },
      });
    },
  },
  Post: {
    user: async (parent, _, { prisma }) => {
      return await prisma.user.findUnique({
        where: {
          id: parent.userId,
        },
      });
    },
  },
};

the only workaround that seems to work is to make those relations (user & posts) optional (remove ! from the end), which does not serve my purpose.

PS: its only a type error and the code is actually working fine.

catinrage avatar Jan 09 '24 08:01 catinrage

solution : https://github.com/dotansimha/graphql-code-generator/issues/1219

catinrage avatar Jan 10 '24 13:01 catinrage