or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

error-handling.mdindex.mdplugins.mdserver-setup.mdtypes.md
tile.json

tessl/npm-apollo-server

Production ready GraphQL Server

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/apollo-server@3.13.x

To install, run

npx @tessl/cli install tessl/npm-apollo-server@3.13.0

index.mddocs/

Apollo Server

Apollo Server is a production-ready TypeScript GraphQL server that provides a batteries-included Express setup. It handles creating the Express app and HTTP server automatically, while offering flexible deployment options, built-in performance optimizations, and comprehensive tooling for development and production monitoring.

Package Information

  • Package Name: apollo-server
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install apollo-server graphql

Core Imports

import { ApolloServer, gql } from 'apollo-server';

For CommonJS:

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

Basic Usage

import { ApolloServer, gql } from 'apollo-server';

// Define GraphQL schema using template literal
const typeDefs = gql`
  type Book {
    title: String
    author: String
  }

  type Query {
    books: [Book]
  }
`;

// Define resolvers
const resolvers = {
  Query: {
    books: () => [
      { title: 'The Awakening', author: 'Kate Chopin' },
      { title: 'City of Glass', author: 'Paul Auster' },
    ],
  },
};

// Create server instance
const server = new ApolloServer({ 
  typeDefs, 
  resolvers,
  // Optional configuration
  cors: true,
  introspection: true,
  playground: true
});

// Start the server
server.listen({ port: 4000 }).then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

Architecture

Apollo Server is built around several key components:

  • Batteries-Included Express Setup: Automatically creates Express app and HTTP server
  • GraphQL Execution Engine: Processes GraphQL queries with schema validation and execution
  • Plugin System: Extensible architecture with built-in plugins for metrics, caching, and development tools
  • Error Handling: Specialized error classes with proper GraphQL formatting
  • Context Management: Request-scoped context for authentication and authorization
  • Performance Optimization: Built-in query parsing, validation caching, and execution optimizations

Capabilities

Server Setup and Configuration

Core server classes for creating GraphQL servers. Includes both the base server class and the batteries-included Express integration.

// Base server class with core GraphQL functionality
class ApolloServerBase<ContextFunctionParams = any> {
  constructor(config: Config<ContextFunctionParams>);
  start(): Promise<void>;
  stop(): Promise<void>;
  executeOperation(request: GraphQLRequest, contextValue?: ContextFunctionParams): Promise<GraphQLResponse>;
}

// Batteries-included Express server
class ApolloServer extends ApolloServerExpress {
  constructor(config: ApolloServerExpressConfig & {
    cors?: CorsOptions | boolean;
    onHealthCheck?: (req: express.Request) => Promise<any>;
    healthCheckPath?: string | null;
    stopGracePeriodMillis?: number;
  });
  
  listen(...opts: Array<any>): Promise<ServerInfo>;
}

interface ServerInfo {
  address: string;
  family: string;
  url: string;
  port: number | string;
  server: http.Server;
}

Server Setup

Schema Definition

GraphQL template literal tag for parsing GraphQL documents with syntax highlighting and validation.

function gql(template: TemplateStringsArray | string, ...substitutions: any[]): DocumentNode;

The gql function is used to define GraphQL schemas and queries with proper parsing and validation.

Plugin System

Comprehensive plugin system with 12+ built-in plugins for metrics, caching, landing pages, and Apollo Studio integration. Plugins provide extensible hooks into the request lifecycle.

interface ApolloServerPlugin<TContext = BaseContext> {
  serverWillStart?(service: GraphQLServiceContext): Promise<GraphQLServerListener | void>;
  requestDidStart?(requestContext: GraphQLRequestContext<TContext>): Promise<GraphQLRequestListener<TContext> | void>;
}

Key plugins include:

  • Usage reporting and schema reporting for Apollo Studio
  • Cache control and inline tracing
  • Landing page customization
  • HTTP server drain for graceful shutdown

Plugins

Error Handling

Specialized GraphQL error classes with proper formatting and extensions. Provides structured error handling with Apollo-specific error codes.

class ApolloError extends Error {
  constructor(message: string, code?: string, extensions?: Record<string, any>);
}

class AuthenticationError extends ApolloError;
class ForbiddenError extends ApolloError;
class UserInputError extends ApolloError;
class ValidationError extends ApolloError;
class SyntaxError extends ApolloError;

function toApolloError(error: Error, code?: string): Error & { extensions: Record<string, any> };

Error Handling

Type System

Complete TypeScript type definitions covering configuration, context management, request/response lifecycle, and plugin development.

interface Config {
  typeDefs?: TypeSource;
  resolvers?: IResolvers | Array<IResolvers>;
  schemaDirectives?: SchemaDirectiveVisitorClass;
  context?: Context<ContextFunctionParams> | ContextFunction<ContextFunctionParams, any>;
  // ... additional configuration options
}

interface GraphQLRequestContext<TContext = BaseContext> {
  readonly request: GraphQLRequest;
  readonly response?: GraphQLResponse;
  readonly context: TContext;
  readonly cache: KeyValueCache;
  // ... additional context properties
}

Types

Utility Functions

HTTP request handling and GraphQL execution utilities for integration development.

function convertNodeHttpToRequest(req: NodeHttpRequest): GraphQLRequest;
function runHttpQuery(options: HttpQueryOptions): Promise<GraphQLResponse>;

interface HttpQueryOptions {
  method: string;
  query: any;
  options: GraphQLOptions;
  request: any;
}

These utilities are primarily used for creating custom Apollo Server integrations.