Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
catinrage opened this issue Jan 9, 2024 · 1 comment
Closed

Comments

@catinrage
Copy link

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
Copy link
Author

solution :
dotansimha/graphql-code-generator#1219

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant