Blogs

Implementing GraphQL Schemas

Let's roll up our sleeves and get our hands dirty with GraphQL schemas. Today, we're not just talking theory—we're diving into the practical side of things. Buckle up, because we're about to implement some GraphQL magic!

Define schema

1. Create a new file named "schema.ts" in the graphql directory. We will use this file for defining all the types for our graphql server.

2. Define the type "Post" which contains the following items

    (a) id

   (b) title

   (c) content

 type Post {
   id: ID!             # id of the post
   title: String!      # title of the post
   content: String!    # textual content of the post
 }

3. Define the type "User" which contains the following items
     (a) id

     (b) username

     (c) email

     (d) posts: this shows how the posts are related to the user

 type User {
   id: ID!              # id of the user
   username: String!    # username of the user
   email: String!       # email of the user
   posts: [Post]        # posts written by the user
 }

4. Define two query types for fetching user and posts

 type Query {
         getUser(id: ID): User    # query that will return user
         posts:[Post]             # query that will return list of post
     }

5. Combine all these types in graphql string and export them as a module

 const typeDefs = `#graphql
     type Query {
         getUser(id: ID): User
         posts:[Post]
     }

     type User {
         id: ID!
         username: String!
         email: String!
         posts: [Post]
     }

     type Post {
         id: ID!
         title: String!
         content: String!
     }
 `;

 export default typeDefs;

6. We can use this exported file in our graphql server instance

 // importing typedefs aka schema
 import typeDefs from "./graphql/schema";

 const server = new ApolloServer({
     typeDefs, // using schema in our graphql server
     resolvers,
 });

Look at that! We're building a cozy space for users and their posts.

Pro Tip: Efficient schema relationships make your app perform like a champ.

You can view and fork the complete example on Github: Implementing graphql Schema

What's next?

In the next blog, we will implement the resolvers for the queries defined in the schema here, and try to understand how the post and user relationship works.