Introduction to Apollo Server
Apollo Server is a popular, open-source GraphQL server that enables you to quickly build a production-ready, self-documenting API. In this guide, we will introduce Apollo Server and explore its various functionalities with code snippets.
Setting Up Apollo Server
const { ApolloServer, gql } = require('apollo-server');
// Type Definitions
const typeDefs = gql`
type Query {
hello: String
}
`;
// Resolvers
const resolvers = {
Query: {
hello: () => 'Hello, world!',
},
};
// Apollo Server Instantiation
const server = new ApolloServer({ typeDefs, resolvers });
// Listening on a port
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
Multiple Queries and Mutations
You can define multiple query and mutation types in your schema:
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
type Mutation {
addBook(title: String, author: String): Book
}
`;
const books = [];
const resolvers = {
Query: {
books: () => books,
},
Mutation: {
addBook: (parent, args) => {
const newBook = { title: args.title, author: args.author };
books.push(newBook);
return newBook;
},
},
};
Integrating Apollo Server with Express
You can also integrate Apollo Server with an existing Express application:
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const app = express();
const server = new ApolloServer({ typeDefs, resolvers });
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () => {
console.log(`Server ready at http://localhost:4000${server.graphqlPath}`);
});
Context
Providing a context to every resolver allows you to pass user authentication details, data loaders, etc.:
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
// For example, user authentication
const token = req.headers.authorization || '';
// Extract the user from the token
// This is just an example; implement your own auth logic here.
const user = getUserFromToken(token);
return { user };
},
});
Error Handling
Handle errors gracefully in your resolvers:
const resolvers = {
Query: {
books: () => {
try {
// Your logic here
return books;
} catch (error) {
throw new Error('Something went wrong');
}
},
},
};
A Complete Example
Here is a complete example application using Apollo Server:
const { ApolloServer, gql } = require('apollo-server');
const books = [
{ title: 'Harry Potter and the Chamber of Secrets', author: 'J.K. Rowling' },
{ title: 'Jurassic Park', author: 'Michael Crichton' },
];
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
type Mutation {
addBook(title: String, author: String): Book
}
`;
const resolvers = {
Query: {
books: () => books,
},
Mutation: {
addBook: (parent, args) => {
const newBook = { title: args.title, author: args.author };
books.push(newBook);
return newBook;
},
},
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
Hash: 5e48e481ae095f39ce95bd847ade6f539ec0d18ecbcaee07ad7af419fed1e481