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.
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}`);
});
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}`);
});
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}`);
});
subscriptions-transport-ws
package for real-time capabilities.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.