This is an Express.js application that serves a GraphQL API for querying books and authors. It uses the express-graphql
middleware to create a GraphQL server.
Here's how you can create a similar app and have fun with it:
-
Import necessary dependencies:
express
: This imports the Express.js framework to create a web server.graphqlHTTP
: This imports theexpress-graphql
middleware for handling GraphQL requests.- Various GraphQL related modules are imported, including types and objects for defining the schema.
-
Define sample data:
- Two arrays,
authors
andbooks
, are defined to serve as sample data for authors and books.
- Two arrays,
-
Define GraphQL Types:
BookType
: This represents the GraphQL type for books. It has fields forid
,title
, andauthor
, whereauthor
is an object of typeAuthorType
. Theresolve
function is used to fetch the author information for a given book based on theauthorId
.AuthorType
: This represents the GraphQL type for authors. It has fields forid
,name
, andbooks
, wherebooks
is a list ofBookType
. Theresolve
function is used to fetch all books associated with a given author.
-
Define Root Query:
RootQueryType
: This represents the root query type for the GraphQL schema. It defines the following query fields:book
: Retrieves a single book by itsid
.books
: Retrieves a list of all books.authors
: Retrieves a list of all authors.author
: Retrieves a single author by theirid
.
-
Create GraphQL Schema:
- The
schema
is created usingGraphQLSchema
, withRootQueryType
as the query root.
- The
-
Set up Express.js Server:
- The Express.js app is initialized using
express()
. - The GraphQL middleware is mounted at the
/graphql
endpoint usingapp.use()
. It uses theschema
defined earlier and enables the GraphiQL interface for easy GraphQL querying during development.
- The Express.js app is initialized using
-
Start the Server:
- The Express.js server listens on port
3000
.
- The Express.js server listens on port