Skip to content

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

Closed
@catinrage

Description

@catinrage

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions