API Reference: apollo-server
This API reference documents the exports from the apollo-server
package.
ApolloServer
The core of an Apollo Server implementation. For an example, see the getting-started article.
constructor(options)
: <ApolloServer
>
Parameters
-
options
: <Object
>typeDefs
: <DocumentNode
> | <Array<DocumentNode>
> (required)
DocumentNode(s) generated by using
gql
tag. They are string representations of GraphQL schema in the Schema Definition Language (SDL).
const typeDefs = gql`
type Author {
name
}
`;
new ApolloServer({
typeDefs,
resolvers,
});
-
resolvers
: <Object
> (required)A map of resolvers for the types defined in
typeDefs
. The key should be the type name and the value should be aFunction
to be executed for that type. -
context
: <Object
> | <Function
>An object or function called with the current request that creates the context shared across all resolvers
new ApolloServer({ typeDefs, resolvers, context: (integrationContext) => ({ // Important: The `integrationContext` argument varies depending // on the specific integration (e.g. Express, Koa, Lambda, etc.) // being used. See the table below for specific signatures. // For example, using Express's `authorization` header, and a // `getScope` method (intentionally left unspecified here): authScope: getScope(integrationContext.req.headers.authorization) }), });
Integration Integration Context Signature Azure Functions {
request:HttpRequest
,
context:Context
}Google Cloud Functions { req:
Request
, res:Response
}Cloudflare { req:
Request
}Express {
req:express.Request
,
res:express.Response
}Fastify {}
hapi {
request:hapi.Request
,
h:hapi.ResponseToolkit
}Koa { ctx:
Koa.Context
}AWS Lambda {
event:APIGatewayProxyEvent
,
context:LambdaContext
}Micro { req:
MicroRequest
, res:ServerResponse
} -
rootValue
: <Any
> | <Function
>A value or function called with the parsed
Document
, creating the root value passed to the graphql executor. The function is useful if you wish to provide a different root value based on the query operation type.
new ApolloServer({
typeDefs,
resolvers,
rootValue: (documentAST) => {
const op = getOperationAST(documentNode)
return op === 'mutation' ? mutationRoot : queryRoot;
}
});
-
mocks
: <Object
> | <Boolean
>A boolean enabling the default mocks or object that contains definitions
-
mockEntireSchema
: <Boolean
>A boolean controlling whether existing resolvers are overridden by mocks. Defaults to true, meaning that all resolvers receive mocked values.
-
schemaDirectives
: <Object
>Contains definition of schema directives used in the
typeDefs
-
introspection
: <Boolean
>Enables and disables schema introspection. Disabled in production by default.
-
playground
: <Boolean
> | <Object
>Enables and disables playground and allows configuration of GraphQL Playground. The options can be found on GraphQL Playground's documentation
-
debug
: <Boolean
>Enables and disables development mode helpers. Defaults to
true
-
validationRules
: <Object
>Schema validation rules
-
tracing
,cacheControl
: <Boolean
>If set to
true
, adds tracing or cacheControl metadata to the GraphQL response. This is primarily intended for use with the deprecated Engine proxy.cacheControl
can also be set to an object to specify arguments to theapollo-cache-control
package, includingdefaultMaxAge
,calculateHttpHeaders
, andstripFormattedExtensions
. -
formatError
,formatResponse
: <Function
>Functions to format the errors and response returned from the server, as well as the parameters to graphql execution(
runQuery
) -
schema
: <Object
>An executable GraphQL schema that will override the
typeDefs
andresolvers
provided. If you are using file uploads, you will have to add theUpload
scalar to the schema, as it is not automatically added in case of setting theschema
manually. -
subscriptions
: <Object
> | <String
> | falseString defining the path for subscriptions or an Object to customize the subscriptions server. Set to false to disable subscriptions
path
: <String
>keepAlive
: <Number
>onConnect
: <Function
>onDisconnect
: <Function
>
-
engine
: <EngineReportingOptions
> | booleanProvided the
ENGINE_API_KEY
environment variable is set, the Graph Manager reporting agent will be started automatically. The API key can also be provided as theapiKey
field in an object passed as theengine
field. See the EngineReportingOptions section for a full description of how to configure the reporting agent, including how to include variable values and HTTP headers. When using the Engine proxy, this option should be set tofalse
. -
persistedQueries
: <Object
> | falseThe persisted queries option can be set to an object containing a
cache
field, which will be used to store the mapping between hash and query string. -
cors
: <Object
|boolean
> (apollo-server)Pass the integration-specific CORS options.
false
removes the CORS middleware andtrue
uses the defaults. This option is only available toapollo-server
. For other server integrations, placecors
inside ofapplyMiddleware
.
Returns
ApolloServer
ApolloServer.listen
Note: This method is only provided by the
apollo-server
package. For theapollo-server-{integration}
packages, seeapplyMiddleware
below.
Parameters
-
options
: <Object
>When using the
apollo-server
package, callinglisten
on an instantiatedApolloServer
will start the server by passing the specified (optional)options
to a Node.jshttp.Server
. For a full reference of the supportedoptions
, see the documentation fornet.Server.listen
.
Returns
Promise
that resolves to an object containing the following properties:
url
: <String
>subscriptionsPath
: <String
>server
: <http.Server
>
ApolloServer.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.Pass the integration-specific cors options. False removes the cors middleware and true uses the defaults.
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`.
ApolloServer.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 String
s), 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
>logger
: <Object
>allowUndefinedInResolve
= falseresolverValidationOptions
= {}directiveResolvers
= nullschemaDirectives
= nullparseOptions
= {}inheritResolversFromInterfaces
= false
addMockFunctionsToSchema(options)
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 withmocks
.
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
apiKey
: string (required)
API key for the service. Obtain an API key from
Graph Manager by logging in and creating
a service. You can also specify an API key with the ENGINE_API_KEY
environment variable, although the apiKey
option takes precedence.
-
calculateSignature
: (ast: DocumentNode, operationName: string) => stringSpecify the function for creating a signature for a query.
See
apollo-graphql
'ssignature.ts
for more information on how the default signature is generated. -
reportIntervalMs
: numberHow often to send reports to Graph Manager, in milliseconds. We'll also send reports when the report reaches a size threshold specified by
maxUncompressedReportSize
. -
maxUncompressedReportSize
: numberIn addition to interval-based reporting, Apollo Server sends a report to Graph Manager whenever the report's size exceeds this value in bytes (default: 4MB). Note that this is a rough limit. The size of the report's header and some other top-level bytes are ignored. The report size is limited to the sum of the lengths of serialized traces and signatures.
-
endpointUrl
: stringThe URL of the Graph Manager report ingress server.
-
requestAgent
:http.Agent | https.Agent | false
HTTP(s) agent to be used for Apollo Graph Manager metrics reporting. This accepts either an
http.Agent
orhttps.Agent
and behaves the same as theagent
parameter to Node.js'http.request
. -
debugPrintReports
: booleanIf set, prints all reports as JSON when they are sent.
-
maxAttempts
: numberReporting is retried with exponential backoff up to this many times (including the original request). Defaults to 5.
-
minimumRetryDelayMs
: numberMinimum backoff for retries. Defaults to 100ms.
-
reportErrorFunction
: (err: Error) => voidBy default, any errors encountered while sending reports to Graph Manager will be logged to standard error. Specify this function to process errors in a different way.
-
sendVariableValues
: { transform: (options: { variables: Record<string, any>, operationString?: string } ) => Record<string, any> } | { exceptNames: Array<String> } | { onlyNames: Array<String> } | { none: true } | { all: true }By default, Apollo Server does not send the values of any GraphQL variables to Apollo's servers, because variable values often contain the private data of your app's users. If you'd like variable values to be included in traces, set this option. This option can take several forms:
{ none: true }
: Don't send any variable values. (DEFAULT){ all: true }
: Send all variable values.{ transform: ({ variables, operationString}) => { ... } }
: A custom function for modifying variable values. Keys added by the custom function will be removed, and keys removed will be added back with an empty value. For security reasons, if an error occurs within this function, all variable values will be replaced with[PREDICATE_FUNCTION_ERROR]
.{ exceptNames: [...] }
: A case-sensitive list of names of variables whose values should not be sent to Apollo servers.{ onlyNames: [...] }
: A case-sensitive list of names of variables whose values will be sent to Apollo servers.
Defaults to not sending any variable values if both this parameter and the deprecated
privateVariables
are not set. The report will indicate each private variable key whose value was redacted by{ none: true }
or{ exceptNames: [...]
}. -
privateVariables
: Array<String> | booleanWill be deprecated in 3.0. Use the option
sendVariableValues
instead. Passing an array intoprivateVariables
is equivalent to passing in{ exceptNames: array }
tosendVariableValues
, and passing intrue
orfalse
is equivalent to passing{ none: true }
or{ all: true }
, respectively.Note: An error will be thrown if both this deprecated option and its replacement,
sendVariableValues
are defined. In order to preserve the old default ofprivateVariables
, which sends all variables and their values, pass in thesendVariableValues
option:new ApolloServer({engine: {sendVariableValues: {all: true}}})
. -
sendHeaders
: { exceptNames: Array<String> } | { onlyNames: Array<String> } | { all: boolean } | { none: boolean } By default, Apollo Server does not send the list of HTTP request headers and values to Apollo's servers, to protect private data of your app's users. If you'd like this information included in traces, set this option. This option can take several forms:{ none: true }
: Drop all HTTP request headers. (DEFAULT){ all: true }
: Send the values of all HTTP request headers.{ exceptNames: [...] }
: A case-insensitive list of names of HTTP headers whose values should not be sent to Apollo servers.{ onlyNames: [...] }
: A case-insensitive list of names of HTTP headers whose values will be sent to Apollo servers.
Defaults to not sending any request header names and values if both this parameter and the deprecated
privateHeaders
are not set. Unlike withsendVariableValues
, names of dropped headers are not reported. The headers 'authorization', 'cookie', and 'set-cookie' are never reported. -
privateHeaders
: Array<String> | booleanWill be deprecated in 3.0. Use the
sendHeaders
option instead. Passing an array intoprivateHeaders
is equivalent to passing{ exceptNames: array }
intosendHeaders
, and passingtrue
orfalse
is equivalent to passing in{ none: true }
and{ all: true }
, respectively.Note: An error will be thrown if both this deprecated option and its replacement,
sendHeaders
, are defined. In order to preserve the old default ofprivateHeaders
, which sends all request headers and their values, pass in thesendHeaders
option:new ApolloServer({engine: {sendHeaders: {all: true}}})
. -
handleSignals
: booleanBy default, EngineReportingAgent listens for the 'SIGINT' and 'SIGTERM' signals, stops, sends a final report, and re-sends the signal to itself. Set this to false to disable. You can manually invoke 'stop()' and 'sendReport()' on other signals if you'd like. Note that 'sendReport()' does not run synchronously so it cannot work usefully in an 'exit' handler.
-
rewriteError
: (err: GraphQLError) => GraphQLError | nullBy default, all errors are reported to Apollo Graph Manager. This function can be used to exclude specific errors from being reported. This function receives a copy of the
GraphQLError
and can manipulate it for the purposes of Graph Manager reporting. The modified error (e.g., after changing theerr.message
property) should be returned or the function should return an explicitnull
to avoid reporting the error entirely. It is not permissible to returnundefined
. Note that mostGraphQLError
fields, likepath
, will be copied from the original error to the new error: this way, you can justreturn new GraphQLError("message")
without having to explicitly keep it associated with the same node. Specifically, only themessage
andextensions
properties on the returnedGraphQLError
are observed. Ifextensions
aren't specified, the originalextensions
are used. -
schemaTag
: StringA human-readable name to tag this variant of a schema (i.e. staging, EU). Setting this value will cause metrics to be segmented in the Apollo Platform's UI. Additionally schema validation with a schema tag will only check metrics associate with the same string.
-
generateClientInfo
: (GraphQLRequestContext) => ClientInfo AS 2.2Creates a client context(ClientInfo) based on the request pipeline's context, which contains values like the request, response, cache, and context. This generated client information will be provided to Graph Manager and can be used to filter metrics. Set
clientName
to identify a particular client. UseclientVersion
to specify a version for a client name. The default function will use theclientInfo
field inside of GraphQL Queryextensions
.For advanced use cases when you already have an opaque string to identify your client (e.g. an API key, x509 certificate, or team codename), use the
clientReferenceId
field to add a reference to its internal identity. This client reference ID will not be displayed in the UI but will be 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 theclientName
as a secondary lookup, so changing aclientName
may result in an unwanted experience.