user776686
user776686

Reputation: 8665

Get other related records (with id different that queried)

As a newbie to GraphQL I would appreciate some help in the following:

I have query which retrieves its author and that author's books. I would like the author's books to be author's other books, meaning - except the one being queried. What does it involve?

apollo-angular query:

const getBookQuery = gql`
    query($id: ID){
        book(id: $id){
            id
            name
            year
            author {
                id
                firstName
                lastName
                books {        # <-- give me all _except_ the one with $id
                    name
                    year
                    id
                }
            }
        }
    }
`;

and in the schema.js (node.js server) I have something like:

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        book: {
            type: BookType,
            args: { id: { type: GraphQLID } },
            resolve(parent, args) {
                const { id } = args;
                return Book.findById(id);
            },
        },
        books: {
            type: GraphQLList(BookType),
            resolve() {
                return Book.find({});
            },
        },
        // ... other queries ...
     }
})

The solution I am looking for should, obviously, not break other queries for books.

Upvotes: 1

Views: 1190

Answers (1)

Greg Brodzik
Greg Brodzik

Reputation: 1817

You should be able to achieve the exclusion by adding an argument to the Author type def and then appropriately using that argument in the resolver for books (which should be nested resolver on your Author type). Will need to adapt syntax for apollo-angular.

    type Author {
       id: 
       firstName: String
       lastName: String 
       books(exclude: ID): [Book]
     }

    const resolverMap = {
      Query: {
        book(arent, args, ctx, info) {
          ...
        }
     },
     Author: {
        books(obj, args, ctx, info) {
          // Use args.exclude passed to filter results
        },
      },
    };

   const getBookQuery = gql`
    query($id: ID){
        book(id: $id){
            id
            name
            year
            author {
                id
                firstName
                lastName
                books(exclude: $id) {        
                    name
                    year
                    id
                }
            }
        }
    }
`;

Upvotes: 2

Related Questions