Skip to content

Latest commit

History

History
735 lines (501 loc) 路 31.8 KB

apollo-server.md

File metadata and controls

735 lines (501 loc) 路 31.8 KB
title sidebar_title api_reference
API Reference: apollo-server
apollo-server
true

This API reference documents the exports from the apollo-server package.

class ApolloServer

The core of an Apollo Server implementation. For an example, see Get started with Apollo Server.

Methods

constructor

Returns an initialized ApolloServer instance.

Takes an options object as a parameter. Supported fields of this object are described in Options.

Example
const server = new ApolloServer({
	typeDefs,
	resolvers
});
Options
Name Type Description

Schema options

typeDefs

DocumentNode or Array<DocumentNode>

Required. Document or documents that represent your server's GraphQL schema, generated by applying the gql tag to valid Schema Definition Language (SDL) strings.

For an example, see Define your GraphQL schema.

resolvers

Object or Array

Required. A map of functions that populate data for individual schema fields. Can also be an array of multiple maps that are merged.

For details, see Resolvers.

context

Object or Function

An object (or a function that creates an object) that's passed to every resolver that executes for a particular operation. This enables resolvers to share helpful context, such as a database connection.

Certain fields are added to this object automatically, depending on which Node.js middleware your server uses.

For more details, see The context argument.

introspection

Boolean

If true, enables schema introspection by clients.

The default value is true, unless the NODE_ENV environment variable is set to production.

schemaDirectives

Object

A map of all custom schema directives used in your schema, if any.

schema

Object

An executable GraphQL schema. You usually don't need to provide this value, because Apollo Server generates it from the typeDefs and resolvers you provide.

This field is most commonly used with Apollo Federation, which uses a special buildFederatedSchema function to generate its schema.

Note that if you are using file uploads, you need to add the Upload scalar to your schema manually before providing it here.

persistedQueries

Object or false

If you're using automated persisted queries (APQ), you can provide an object with a cache field as the value of this option to customize where Apolllo Server stores the mapping between operation hashes and query strings.

Provide false to disable APQ entirely.

subscriptions

Object or String or false

Provide a String to specify the server's subscription-specific endpoint, or an Object to further configure subscription behavior.

Provide false to disable subscription operations entirely.

rootValue

Any or Function

A value or function called with the parsed Document, creating the root value passed to the GraphQL executor.

Providing a function is useful if you want to use a different root value depending on the operation's details, such as whether it's a query or mutation.

validationRules

Object

An object containing custom functions to use as additional validation rules when validating the schema.

Networking options

engine

EngineReportingOptions

An object containing configuration options for connecting Apollo Server to Apollo Studio.

Supported fields are described in EngineReportingOptions.

cors

Object or Boolean

An Object containing configuration options for the server's CORS behavior. Provide false to remove CORS middleware entirely.

This option is used only by the apollo-server package. If you're integrating with Node.js middleware via a different package, instead see applyMiddleware.

formatError

Function

Provide this function to transform the structure of error objects before they're sent to a client. The function takes a GraphQLError object and should return a GraphQLFormattedError object.

formatResponse

Function

Provide this function to transform the structure of GraphQL response objects before they're sent to a client. The function takes a GraphQLResponse object and a GraphQLRequestContext object, and it should return a GraphQLResponse object.

Lifecycle options

stopOnTerminationSignals

Boolean

By default (when running in Node and when the NODE_ENV environment variable does not equal test), ApolloServer listens for the SIGINT and SIGTERM signals and calls await this.stop() on itself when it is received, and then re-sends the signal to itself so that process shutdown can continue. Set this to false to disable this behavior, or to true to enable this behavior even when NODE_ENV is test. You can manually invoke stop() in other contexts if you'd like. Note that stop() does not run synchronously so it cannot work usefully in an process.on('exit') handler.

Debugging options

playground

Boolean or Object

If truthy, the server hosts GraphQL Playground from its URL. Can be an object to pass configuration options to the playground.

The default value is true, unless the NODE_ENV environment variable is set to production.

Note that introspection must be enabled for GraphQL Playground to function properly.

debug

Boolean

If true, enables development mode helpers and logs messages of all severity levels (debug through error). If false, only warn- and error-level messages are logged.

Defaults to true.

logger

Logger

An object to use for logging in place of console. If provided, this object must implement all methods of the Logger interface.

If you provide this value, Apollo Server automatically logs all messages of all severity levels (debug through error), regardless of whether the debug option is set to true. It is the responsibility of the logger to determine how to handle logged messages of each level.

This logger is automatically added to the GraphQLRequestContext object that's passed to all Apollo Server plugin functions.

mocks

Boolean or Object

If true, enables default mock resolvers for schema fields. If an object, enables custom mock resolvers based on the object's fields.

mockEntireSchema

Boolean

If true and mocks is also specified, mock resolvers are enabled even for fields that you've defined a resolver for.

The default value is true. Set this to false to use mocked resolvers only for fields that you haven't defined a resolver for.

  • experimental_approximateDocumentStoreSizeMiB
    • number
    • This option is experimental. It might be removed or change at any time, even within a patch release.

      Sets the approximate size (in MiB) of the server's DocumentNode cache. The server checks the SHA-256 hash of each incoming operation against cached DocumentNodes, and skips unnecessary parsing and validation if a match is found.

      The cache's default size is 30MiB, which is usually sufficient unless the server processes a large number of unique operations.

Middleware-specific context fields

The context object passed between Apollo Server resolvers automatically includes certain fields, depending on which Node.js middleware you're using:

Middleware Context fields
AWS Lambda {
聽聽event: APIGatewayProxyEvent,
聽聽context: LambdaContext
}
Azure Functions {
聽聽request: HttpRequest,
聽聽context: Context
}
Cloudflare { req: Request }
Express {
聽聽req: express.Request,
聽聽res: express.Response
}
Fastify {}
Google Cloud Functions { req: Request, res: Response }
hapi {
聽聽request: hapi.Request,
聽聽h: hapi.ResponseToolkit
}
Koa { ctx: Koa.Context }
Micro { req: MicroRequest, res: ServerResponse }
Subscription configuration fields

Apollo Server supports the following fields of an object you provide to the subscriptions option of the ApolloServer constructor:

Name Type Description
path

String

Required. The URL for the server's subscription-specific endpoint.

keepAlive

Number

The frequency with which the subscription endpoint should send keep-alive messages to open client connections, in milliseconds, if any.

If this value isn't provided, the subscription endpoint doesn't send keep-alive messages.

onConnect

Function

A lifecycle hook that's called whenever a subscription connection is initiated by a client. See an example

onDisconnect

Function

A lifecycle hook that's called whenever a subscription connection is terminated by a client.

listen

Instructs Apollo Server to begin listening for requests.

This method is provided only by the apollo-server package. If you're integrating with Node.js middleware via a different package (such as apollo-server-express, instead see applyMiddleware.

Parameters
  • options: <Object>

    When using the apollo-server package, calling listen on an instantiated ApolloServer will start the server by passing the specified (optional) options to a Node.js http.Server. For a full reference of the supported options, see the documentation for net.Server.listen.

Returns

Promise that resolves to an object containing the following properties:

  • url: <String>
  • subscriptionsPath: <String>
  • server: <http.Server>

applyMiddleware

The applyMiddleware method is provided by the apollo-server-{integration} packages that use middleware, such as hapi and express. This method connects ApolloServer to a specific HTTP framework.

Parameters
  • options: <Object>

    • app: <HttpServer> (required)

      Pass an instance of the server integration here.

    • path : <String>

      Specify a custom path. It defaults to /graphql if no path is specified.

    • cors: <Object | boolean> (express, hapi, koa)

      Pass the integration-specific cors options. False removes the cors middleware and true uses the defaults.

    • bodyParserConfig: <Object | boolean> (express, koa)

      Pass the body-parser options. False removes the body parser middleware and true uses the defaults.

Usage

The applyMiddleware method from apollo-server-express registration of middleware as shown in the example below:

const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const { typeDefs, resolvers } = require('./schema');

const server = new ApolloServer({
  // These will be defined for both new or existing servers
  typeDefs,
  resolvers,
});

const app = express();
// Additional middleware can be mounted at this point to run before Apollo.
app.use('*', jwtCheck, requireAuth, checkScope);

server.applyMiddleware({ app, path: '/specialUrl' }); // app is from an existing express app. Mount Apollo middleware here. If no path is specified, it defaults to `/graphql`.

getMiddleware

Similar to the applyMiddleware method above, though rather than applying the composition of the various Apollo Server middlewares which comprise a full-featured Apollo Server deployment (e.g. middleware for HTTP body parsing, GraphQL Playground, uploads and subscriptions) the getMiddleware simply returns the middleware.

The getMiddleware method takes the same arguments as applyMiddleware except app should not be passed. Instead, the result of getMiddleware must be added as a middleware directly to an existing application (e.g. with app.use(...)).

For example, for apollo-server-express, this means that rather than passing applyMiddleware an app which was already initiated from calling express(), and applyMiddleware "using" (i.e. app.use), the implementor will instead call app.use(...) on the result of getMiddleware with the same arguments.

gql

The gql is a template literal tag. Template literals were introduced in recent versions of ECMAScript to provide embedded expressions (i.e. `A string with interpolated ${variables}`) and template literal tags exist to provide additional functionality for what would otherwise be a normal template literal.

In the case of GraphQL, the gql tag is used to surround GraphQL operation and schema language (which are represented as Strings), and makes it easier to differentiate from ordinary strings. This is particularly useful when performing static analysis on GraphQL language (e.g. to enable syntax highlighting, code generation, etc.) and avoids need for tools to "guess" if a string contains GraphQL language.

Usage

Import the gql template literal tag into the current context from the apollo-server or apollo-server-{integration} modules:

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

Then, place GraphQL schema definitions (SDL), queries or other operations into the gql template literal tag. Keep in mind that template literals use the grave accent (`) and not normal quotation marks (e.g. not " or '):

const typeDefs = gql`
  type Author {
    name
  }
`;

makeExecutableSchema

The makeExecutableSchema method is re-exported from apollo-server as a convenience.

Parameters

  • options : <Object>
    • typeDefs: <GraphQLSchema> (required)
    • resolvers : <Object> : <Array<Object>>
    • logger : <Object>
    • allowUndefinedInResolve = false
    • resolverValidationOptions = {}
    • directiveResolvers = null
    • schemaDirectives = null
    • parseOptions = {}
    • inheritResolversFromInterfaces = false

addMockFunctionsToSchema

The addMockFunctionsToSchema method is re-exported from apollo-server as a convenience.

Given an instance of a GraphQLSchema and a mock object, modifies the schema (in place) to return mock data for any valid query that is sent to the server.

If preserveResolvers is set to true, existing resolve functions will not be overwritten to provide mock data. This can be used to mock some parts of the server and not others.

Parameters

  • options: <Object>

    • schema: <GraphQLSchema> (required)

      Pass an executable schema (GraphQLSchema) to be mocked.

    • mocks: <Object>

      Should be a map of types to mock resolver functions, e.g.:

      {
        Type: () => true,
      }

      When mocks is not defined, the default scalar types (e.g. Int, Float, String, etc.) will be mocked.

    • preserveResolvers: <Boolean>

      When true, resolvers which were already defined will not be over-written with the mock resolver functions specified with mocks.

Usage

const { addMockFunctionsToSchema } = require('apollo-server');

// We'll make an assumption that an executable schema
// is already available from the `./schema` file.
const executableSchema = require('./schema');

addMockFunctionsToSchema({
  schema: executableSchema,
  mocks: {
    // Mocks the `Int` scalar type to always return `12345`.
    Int: () => 12345,

    // Mocks the `Movies` type to always return 'Titanic'.
    Movies: () => 'Titanic',
  },
  preserveResolvers: false,
});

EngineReportingOptions

These are the supported fields of the engine object you provide to the ApolloServer constructor to configure communication with Apollo Studio.

Name Type Description
Base config
apiKey String

The graph API key that Apollo Server should use to authenticate with Apollo Studio.

Instead of using this field, we recommend providing your API key by setting it as the value of the APOLLO_KEY environment variable in your server's environment.

graphVariant String

The variant of your graph to associate this server's schema and metrics with.

Instead of using this field, we recommend specifying a variant by setting its name as the value of the APOLLO_GRAPH_VARIANT environment variable in your server's environment.

logger Logger

If you provide this object, Apollo Server sends it all log messages related to Apollo Studio communication, instead of sending them to the default logger. The object must implement all methods of the Logger interface.

Schema reporting
reportSchema Boolean

If true, Apollo Server begins periodically reporting its schema to Apollo Studio shortly after startup.

The default value is false.

schemaReportingInitialDelayMaxMs Number

On startup, Apollo Server waits a random amount of time between 0 milliseconds and this value before it begins reporting its schema. This randomness is useful for staggering schema reports when you deploy multiple server instances simultaneously.

The default value is 10 seconds (10000). You might want to reduce this value in constrained environments, such as AWS Lambda.

overrideReportedSchema String

By default, Apollo Server normalizes its schema before reporting it to Apollo Studio. Doing so helps make sure that no-op changes to a schema's whitespace or field order aren't incorrectly identified as an updated schema.

If normalization removes details that you want to preserve, you can provide an SDL string directly to this option. If you do, it is reported directly to Studio instead of the server's normalized schema.

Metrics reporting
reportIntervalMs Number

The interval at which Apollo Server should send batched trace reports to Studio, in milliseconds.

Regardless of this value, Apollo Server sends a trace report whenever the size of a pending batch exceeds the value of maxUncompressedReportSize (default 4MB).

maxUncompressedReportSize Number

Apollo Server sends a trace report whenever the size of a pending batched trace report exceeds this value (in bytes), regardless of its standard reporting interval.

The default value is 4MB (4194304).

maxAttempts Number

The maximum number of times Apollo Server should attempt to report each trace report, performing exponential backoff between attempts.

The default value is 5.

minimumRetryDelayMs Number

The minimum amount of backoff (in milliseconds) Apollo Server should perform before retrying a failed trace report.

The default value is 100.

reportTiming async Function or Boolean

Provide this async function to determine whether to report metrics to Apollo Studio on an operation-by-operation basis.

This function is called once per operation. It is passed either a GraphQLRequestContextDidResolveOperation object (on operation success) or a GraphQLRequestContextDiDEncounterErrors object (if errors occurred). It should return a Promise that resolves to a boolean (metrics are not reported if false).

By default, Apollo Server reports metrics for all operations if reporting is enabled.

sendHeaders Object

Provide this object to configure which request header names and values are included in trace data that's sent to Apollo Studio. Valid options are described in Valid sendHeaders object signatures.

The default value is { none: true }, which means no header names or values are sent to Studio. This is a security measure to prevent sensitive data from potentially reaching Apollo servers.

sendVariableValues Object

Provide this object to configure which GraphQL variable values are included in trace data that's sent to Apollo Studio. Valid options are described in Valid sendVariableValues object signatures.

The default value is { none: true }, which means no variable values are sent to Studio. This is a security measure to prevent sensitive data from potentially reaching Apollo servers.

debugPrintReports Boolean

If true, Apollo Server logs a message whenever a trace report is sent or a reporting error occurs.

The default value is false.

reportErrorFunction Function

If you provide this function, Apollo Server calls it whenever it encounters an error while reporting metrics. The details of the error are passed to the function.

By default, Apollo Server logs these errors to stderr.

rewriteError Function

Specify this function to modify GraphQL operation errors before Apollo Server reports those errors to Apollo Studio. The function takes a GraphQLError object and must also return one (or null to prevent Apollo Server from reporting a particular error entirely).

The only properties of the reported error you can modify are its message and its extensions.

requestAgent http.Agent or https.Agent or false An HTTP(S) agent to use for metrics reporting. Can be either an http.Agent or an https.Agent. It behaves the same as the agent parameter to http.request.
generateClientInfo Function

Specify this function to provide Apollo Studio with client details for each processed operation. Apollo Studio uses this information to segment metrics by client.

The function is passed a GraphQLRequestContext object containing all available information about the request. It should return a ClientInfo object describing the associated GraphQL client.

By default, Apollo Server attempts to obtain ClientInfo fields from the clientInfo field of the GraphQL operation's extensions.

For advanced use cases when you already use an opaque string to identify your client (such as an API key, x509 certificate, or team codename), use the clientReferenceId field to add a reference to that internal identity. The reference ID is not displayed in Studio, but it is available for cross-correspondence, so names and reference IDs should have a one-to-one relationship.

Warning: If you specify a clientReferenceId, Graph Manager will treat the clientName as a secondary lookup, so changing a clientName may result in an unwanted experience.

calculateSignature Function

A custom function to use to calculate the "signature" of the schema that operations are running against. This enables Apollo Studio to detect when two non-identical schema strings represent the exact same underlying model.

For an example, see the default signature function, which sorts types and fields, removes extraneous whitespace, and removes unused definitions.

handleSignals Boolean

For backwards compatibility only; specifying new ApolloServer({engine: {handleSignals: false}}) is equivalent to specifying new ApolloServer({stopOnTerminationSignals: false})

Valid sendHeaders object signatures

You can provide an object with one of the following structures as the value of the sendHeaders option in EngineReportingOptions.

Regardless of your configuration, Apollo Server never sends the values of the following headers to Apollo Studio:

  • authorization
  • cookie
  • set-cookie
Object Description
{ none: true } If you provide this object, no request header names or values are sent to Apollo Studio. This is the default behavior.
{ all: true } If you provide this object, all GraphQL header names and values are sent to Apollo Studio, except for the protected headers listed above.
{ onlyNames: ["apple", "orange"]} If you provide an object with this structure, only names and values of the request headers with names that appear in the array are sent to Apollo Studio. Case-insensitive.
{ exceptNames: ["apple", "orange"]} If you provide an object with this structure, all GraphQL header values except values of headers with names that appear in the array are sent to Apollo Studio. Case-insensitive.
Valid sendVariableValues object signatures

You can provide an object with one of the following structures as the value of the sendVariableValues option in EngineReportingOptions.

Object Description
{ none: true } If you provide this object, no GraphQL variable values are sent to Apollo Studio. This is the default behavior.
{ all: true } If you provide this object, all GraphQL variable values are sent to Apollo Studio.
{ onlyNames: ["apple", "orange"]} If you provide an object with this structure, only values of the GraphQL variables with names that appear in the array are sent to Apollo Studio. Case-sensitive.
{ exceptNames: ["apple", "orange"]} If you provide an object with this structure, all GraphQL variable values except values of variables with names that appear in the array are sent to Apollo Studio. Case-sensitive.
{ transform: ({ variables, operationString)} => { ... } }

The value of transform is a function that takes the values of all GraphQL variables for an operation. The function should modify or delete necessary values in the variables map and return the result. You cannot add variables to the map.

For security reasons, if an error occurs in the transform function, all variable values are replaced with [PREDICATE_FUNCTION_ERROR].