DeveloperBreeze

Setting Up the Server

  1. Initialize the Project

First, create a new directory for your project and initialize it with npm:

   mkdir graphql-server
   cd graphql-server
   npm init -y
  1. Install Dependencies

Install the required packages:

   npm install express apollo-server-express graphql
  1. Create the Server Code

Create an index.js file and add the following code:

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

// Sample data
let books = [
    { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
    { title: 'To Kill a Mockingbird', author: 'Harper Lee' },
];

// GraphQL schema definition
const typeDefs = gql`
    type Book {
        title: String!
        author: String!
    }

    type Query {
        books: [Book]
    }

    type Mutation {
        addBook(title: String!, author: String!): Book
    }
`;

// GraphQL resolvers
const resolvers = {
    Query: {
        books: () => books,
    },
    Mutation: {
        addBook: (_, { title, author }) => {
            const newBook = { title, author };
            books.push(newBook);
            return newBook;
        },
    },
};

// Create Apollo server
const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

app.listen({ port: 4000 }, () =>
    console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);

Features of the GraphQL Server

  • Schema Definition: The typeDefs defines a simple schema with a Book type and queries to fetch books and add a new book.
  • Resolvers: Functions that resolve the queries and mutations. In this case, they return all books and add a new book to the list.

How to Use

  1. Start the Server

Run the server using Node.js:

   node index.js
  1. Access the GraphQL Playground

Open a browser and go to http://localhost:4000/graphql. You'll see the Apollo GraphQL Playground, where you can test your queries and mutations.

  1. Example Queries
  • Fetch Books
     query {
       books {
         title
         author
       }
     }
  • Add a Book
     mutation {
       addBook(title: "1984", author: "George Orwell") {
         title
         author
       }
     }

Benefits of GraphQL

  • Flexible Queries: Allows clients to request only the data they need, reducing over-fetching.
  • Strongly Typed: Ensures data consistency and helps with error handling.
  • Single Endpoint: All data operations occur through a single endpoint, simplifying network requests.

Continue Reading

Handpicked posts just for you — based on your current read.

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!