0

I have a type User and a type Book defined as below:

type User { id: ID! borrowedBooks: [Book] } type Book { id: ID! name: String borrowedBy: [User] } 

Now I'd like to store the user's rating to each book. My question is: How should I define the schema so that I can query the user's rating to each borrowed book? Is it possible for me to query the rating like below, and if not, what is the common method to deal with situations like this.

getUser(id: "xxx"): { borrowedBooks: { id name rating # <------ get the rating value } } 
2
  • Your schema doesn't determine how you fetch data from whatever data sources GraphQL is sitting in front of, that's what your resolver logic does. At worst, a schema can make fetching data from those data sources less efficient than it could be. Are you asking in the context of a specific data source, or some specific implementation of GraphQL, like AWS AppSync? Commented Oct 28, 2018 at 20:19
  • Hi @DanielRearden, thank you for the reply. Yeah, I see what you mean, depending on what data source used, one might have to define resolvers and even schemas differently. I guess I have two questions. The first is how to define a schema for that use case (the query method doesn't have to be the same as what I wrote, just want to know how do other devs like yourself deal with that). And the second question is how to actually revolve it. You're right I am using AppSync. It would be great to know how to do it in AppSync, or at least test if AppSync can actually transform the resolvers correctly. Commented Oct 29, 2018 at 3:56

1 Answer 1

1

It's generally bad practice to add fields to a type that will only be populated in a specific context. You could add a rating to the Book type, but then you would only resolve it with a value when fetching a list of books that have been borrowed -- if you're fetching a book or an array of books for some other field, a rating field may not necessarily make sense.

What you probably want is another type (and another table, if we're talking about the underlying database) to join the user with their borrowed books. Something like:

type User { id: ID! checkouts: [Checkout] } type Book { id: ID! name: String checkouts: [Checkout] } type Checkout { user: User book: Book rating: Int lastCheckoutDate: Date # other fields specific to the checkout itself } 

This makes the resulting data returned by a query a bit more nested, but it also makes the data easier to model and reason about. The resolvers for these fields can then also be relatively straightforward -- the checkouts field for User and Book just gets all Checkouts by User or Book id. The user and book fields on Checkout just query the User or Book by id.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.