Search code examples
typescriptapigraphqltypeormtypegraphql

How to resolve array entities in a GraphQL-Query?


I have a graphql Query in which i am trying to get All the fields of Post.

{
    getSpaceByName(spaceName: "Anime") {
        spaceId
        spaceName
        spaceAvatarUrl
        spaceDescription
        followingIds {
            User {
                id
                name
                username
            }
        }
    }
}

In this query there is a followingIds Array which is an Array of strings which contain all the Ids of users who follow this page. Then i use a Field Resolver to resolver all these ids and resturn an array of users

  @FieldResolver(() => User)
  async followingIds(@Root() space: Spaces) {
    const spaceAcc = (await Spaces.findOne({
      where: {
        spaceName: space.spaceName,
      },
    })) as Spaces;
   const users  = []
   await users.push(await User.findByIds(spaceAcc.followingIds as string[]) as User[])
   console.log(users)
   return users
  }

This is what i am getting from my server this is the result

And this is the error i get when i use to call this in my GraphQL Query. enter image description here

How to resolve this User instance i am getting into all the user fields and return it withing my Graphql-Query?


Solution

  • Try changing your field resolver like this:

    @FieldResolver(() => [User])
    async followingIds(@Root() space: Spaces) {
      const spaceAcc = (await Spaces.findOne({
        where: {
          spaceName: space.spaceName,
        },
      })) as Spaces;
      const users  = await User.findByIds(spaceAcc.followingIds as string[]) as User[];
      console.log(users);
      return users;
    }
    

    Then change your query like below:

    {
        getSpaceByName(spaceName: "Anime") {
            spaceId
            spaceName
            spaceAvatarUrl
            spaceDescription
            followingIds {
                id
                name
                username
            }
        }
    }