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

Discover more amazing content handpicked just for you

Tutorial

Build a Custom Rate Limiter in Node.js with Redis

// rateLimiter.js
const client = require("./redisClient");

const rateLimiter = (limit = 100, windowSec = 3600) => {
  return async (req, res, next) => {
    const ip = req.ip;
    const key = `rate_limit:${ip}`;

    const current = await client.get(key);

    if (current !== null && parseInt(current) >= limit) {
      return res.status(429).json({ error: "Too many requests. Try later." });
    }

    const multi = client.multi();
    multi.incr(key);
    if (!current) {
      multi.expire(key, windowSec);
    }
    await multi.exec();

    next();
  };
};

module.exports = rateLimiter;
// server.js
require("dotenv").config();
const express = require("express");
const rateLimiter = require("./rateLimiter");

const app = express();
const PORT = 3000;

app.use(rateLimiter(100, 3600)); // 100 requests/hour per IP

app.get("/", (req, res) => {
  res.send("Welcome! You're within rate limit.");
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Apr 04, 2025
Read More
Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

Explanation:

  • require('sqlite3').verbose(): Imports the sqlite3 module with verbose error logging enabled.
  • new sqlite3.Database('your_database_name.db'): Creates a new SQLite database file named your_database_name.db. If the file doesn't exist, SQLite will create it.

Oct 24, 2024
Read More
Cheatsheet

REST API Cheatsheet: Comprehensive Guide with Examples

No preview available for this content.

Aug 24, 2024
Read More
Cheatsheet

Comprehensive React Libraries Cheatsheet

No preview available for this content.

Aug 21, 2024
Read More
Cheatsheet
mysql

MySQL Cheatsheet: Comprehensive Guide with Examples

No preview available for this content.

Aug 20, 2024
Read More
Tutorial
javascript php

Integrating Laravel and React with Vite: Using Databases and PHP in a Full-Stack Project

For applications requiring authentication, Laravel offers built-in tools like Sanctum or Jetstream. You can protect API routes and access them from React using tokens or cookies.

To protect API routes, use Laravel’s middleware:

Aug 14, 2024
Read More
Tutorial
go

Building a RESTful API with Go and Gorilla Mux

   curl -X GET http://localhost:8000/books/b1
   curl -X PUT http://localhost:8000/books/b1 -H "Content-Type: application/json" -d '{"title":"Advanced Go","author":"Jane Smith","year":"2024"}'

Aug 12, 2024
Read More
Tutorial
javascript nodejs +1

Building a GraphQL API with Node.js and Apollo Server

  mutation {
    addBook(title: "1984", author: "George Orwell") {
      title
      author
    }
  }

Once you have a basic GraphQL server set up, you can explore more advanced features such as arguments, variables, and real-time subscriptions.

Aug 12, 2024
Read More
Code
javascript

React Custom Hook for API Requests

import React from 'react';
import useFetch from './useFetch'; // Ensure correct import path

function UserList() {
    const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users');

    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error: {error.message}</p>;

    return (
        <ul>
            {data.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

export default UserList;
  • Reusability: The useFetch hook can be used across different components and applications, reducing code duplication and simplifying API interaction.
  • Loading and Error States: Automatically manages loading and error states, providing a consistent way to handle asynchronous operations.
  • Cleanup Handling: Prevents state updates on unmounted components, reducing potential memory leaks and ensuring stability.

Aug 12, 2024
Read More
Code
javascript python +1

Generate Random Password

No preview available for this content.

Jan 26, 2024
Read More
Code
php

Convert a human-readable date into a MySQL-compatible date format

No preview available for this content.

Jan 26, 2024
Read More
Code
php

Generate MySQL-Formatted Dates

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Filter SQLAlchemy Query for Records Created Between Specific Dates

No preview available for this content.

Jan 26, 2024
Read More
Code
php

Date Formatting for Specific Date ('Y-m-d')

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!