I am new to GraphQL and I cannot understand what is the correct way of resolving queries when the database fields are different from the GraphQL schema fields.
I am using Apollo Server.
My DB schema is like this one:
// db schema
type Book {
id: number
title: string
author_id: number
}
type Author {
id: number
name: string
}
My GraphQL schema must be like this one:
// gql schema
type Book {
title: String!
author: Author!
}
type Author {
name: String!
books: [Book]!
}
type Query {
author(id: ID!): Author
book(id: ID!): Book
authors: [Author]
books: [Book]
}
Now what I understood is that I have to manually translate the database object to the graphql response object with resolvers.
So these are my resolvers:
const resolvers:Resolvers = {
Book: {
author: async (parent, args, context, info) => {
const authors = await db.author.select({where: {id: parent.author_id}});
~~~~~~~~~~~~~~~~~~~~~ -> FIRST PROBLEM
return authors[0];
}
},
Author: {
books: async (parent, args, context, info) => {
const books = await db.books.select({where: {author_id: parent.id}});
return books;
}
},
Query: {
book: async (parent, args, context, info) => {
const books = await db.author.select({where: {id: args.id}});
return books[0];
~~~~~~~~~~~~~~~~ -> SECOND PROBLEM
}
author: async (parent, args, context, info) => {
const authors = await db.author.select({where: {id: args.id}});
return authors[0];
~~~~~~~~~~~~~~~~~ -> SAME AS SECOND PROBLEM
},
books: async (parent, args, context, info) => {
const books = await db.books.select();
return books;
}
authors: async (parent, args, context, info) => {
const authors = await db.authors.select();
return authors;
}
}
}
FIRST PROBLEM:
When I resolve the author field in Book, I don't have the author_id fields because it is not defined in the graphql schema.
Should I always add author_id also in the GQL Schema?
SECOND PROBLEM:
How can I resolve the Author in Query.book? Is there a proper way to resolve it? I don't want to make another DB call, because this will lead me to an infinite loop, right?
SAME AS SECOND PROBLEM:
How can I resolve the [Book] in Query.author? Is there a proper way to resolve the it?
I put these problems together because I think they are all related to the same solutions somehow. I just cannot see it.
Can somebody know how to solve it?