GraphQL with Node.js: 3 Practical Examples

Explore three detailed examples of using GraphQL with Node.js to build efficient APIs.
By Jamie

Introduction to GraphQL with Node.js

GraphQL is a powerful query language for APIs that enables clients to request exactly the data they need. By using GraphQL with Node.js, developers can create flexible and efficient APIs that cater to the front-end needs without over-fetching or under-fetching data. Here are three practical examples that demonstrate how to implement GraphQL in a Node.js environment.

Example 1: Creating a Simple GraphQL API for a Book Store

Context

In this example, we will create a simple GraphQL API for managing a collection of books. This API will allow users to query for books and add new ones to the collection.

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

// Sample data
const books = [
  { title: '1984', author: 'George Orwell' },
  { title: 'To Kill a Mockingbird', author: 'Harper Lee' }
];

// GraphQL schema
const typeDefs = gql`
  type Book {
    title: String
    author: String
  }
  type Query {
    books: [Book]
  }
  type Mutation {
    addBook(title: String, author: String): Book
  }
`;

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

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}`);
});

Notes

  • This API can be expanded with more features, such as updating or deleting books.
  • Use tools like GraphiQL or Postman to test the API.

Example 2: Integrating GraphQL with a Database

Context

In this example, we will integrate GraphQL with a MongoDB database to manage user profiles. The API will allow querying user information and creating new user profiles.

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

// Connect to MongoDB
mongoose.connect('mongodb://localhost/userdb', { useNewUrlParser: true, useUnifiedTopology: true });

const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
});
const User = mongoose.model('User', UserSchema);

// GraphQL schema
const typeDefs = gql`
  type User {
    id: ID
    name: String
    email: String
  }
  type Query {
    users: [User]
  }
  type Mutation {
    addUser(name: String, email: String): User
  }
`;

// Resolvers
const resolvers = {
  Query: {
    users: () => User.find(),
  },
  Mutation: {
    addUser: async (parent, { name, email }) => {
      const user = new User({ name, email });
      await user.save();
      return user;
    },
  },
};

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}`);
});

Notes

  • Ensure MongoDB is running before executing this code.
  • You can use tools like MongoDB Compass to view your database.

Example 3: Using GraphQL Subscriptions for Real-Time Updates

Context

In this example, we will implement GraphQL subscriptions to provide real-time updates for a chat application. Users will be able to send messages and receive updates instantly.

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const { createServer } = require('http');
const { SubscriptionServer } = require('subscriptions-transport-ws');
const { execute, subscribe } = require('graphql');

const messages = [];

const typeDefs = gql`
  type Message {
    content: String
  }
  type Query {
    messages: [Message]
  }
  type Mutation {
    sendMessage(content: String): Message
  }
  type Subscription {
    messageSent: Message
  }
`;

const resolvers = {
  Query: {
    messages: () => messages,
  },
  Mutation: {
    sendMessage: (parent, { content }) => {
      const message = { content };
      messages.push(message);
      pubsub.publish('MESSAGE_SENT', { messageSent: message });
      return message;
    },
  },
  Subscription: {
    messageSent: {
      subscribe: () => pubsub.asyncIterator('MESSAGE_SENT'),
    },
  },
};

const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
const httpServer = createServer(app);
server.applyMiddleware({ app });

httpServer.listen({ port: 4000 }, () => {
  new SubscriptionServer({
    execute,
    subscribe,
    schema: server.schema,
  }, {
    server: httpServer,
    path: server.graphqlPath,
  });
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
});

Notes

  • This example requires the subscriptions-transport-ws package for real-time capabilities.
  • Use a web socket client to test subscriptions.

These examples illustrate the versatility of GraphQL when combined with Node.js, showcasing how to build APIs that can efficiently handle data retrieval and real-time updates.