Building with Apollo Server

◕ GraphQLLesson 9Intermediate

Apollo Server is the most popular GraphQL server library for Node.js. It integrates with Express, provides built-in error handling, a Sandbox explorer, and supports plugins for logging, caching, and tracing.

1 Standalone Apollo Server Setup
Terminal — Install Apollo Server
npm install @apollo/server graphql
JavaScript — server.js
const { ApolloServer } = require("@apollo/server");
const { startStandaloneServer } = require("@apollo/server/standalone");

const typeDefs = `
  type User {
    id: ID!
    name: String!
    email: String!
  }
  type Query {
    users: [User!]!
    user(id: ID!): User
  }
  type Mutation {
    createUser(name: String!, email: String!): User!
  }
`;

// In-memory data
const users = [{ id: "1", name: "Balaji", email: "b@example.com" }];

const resolvers = {
  Query: {
    users: () => users,
    user: (_, { id }) => users.find(u => u.id === id)
  },
  Mutation: {
    createUser: (_, { name, email }) => {
      const user = { id: String(users.length + 1), name, email };
      users.push(user);
      return user;
    }
  }
};

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

const { url } = await startStandaloneServer(server, {
  listen: { port: 4000 },
  context: async ({ req }) => {
    return { token: req.headers.authorization };
  }
});
console.log("GraphQL Server ready at:", url);
2 Apollo Server with Express (Production)
JavaScript — Express Integration
const express = require("express");
const { ApolloServer } = require("@apollo/server");
const { expressMiddleware } = require("@apollo/server/express4");
const cors    = require("cors");
const { json } = require("body-parser");

const app    = express();
const server = new ApolloServer({ typeDefs, resolvers });

await server.start();

app.use(
  "/graphql",
  cors(),
  json(),
  expressMiddleware(server, {
    context: async ({ req }) => buildContext(req)
  })
);

// Can still add regular REST routes
app.get("/health", (_, res) => res.json({ status: "ok" }));

app.listen(4000, () => console.log("Server ready on port 4000"));
3 Error Handling
JavaScript — Apollo GraphQL Errors
const { GraphQLError } = require("graphql");

const resolvers = {
  Query: {
    user: async (_, { id }, { currentUser }) => {
      if (!currentUser) {
        throw new GraphQLError("Not authenticated", {
          extensions: { code: "UNAUTHENTICATED" }
        });
      }
      const user = await User.findById(id);
      if (!user) {
        throw new GraphQLError("User not found", {
          extensions: { code: "NOT_FOUND", id }
        });
      }
      return user;
    }
  }
};
4 Code Challenge
Challenge: Build a fully working Apollo Server with a Product type. Implement products query (with optional category filter), product(id) query, createProduct mutation, and proper error handling for not-found cases.