A set of MakerX plugins for Apollo Server
graphqlOperationLoggingPlugin logs GraphQL operations using the logger from the GraphQL context.
Logging is performed via the willSendResponse and willSendSubsequentPayload hooks, which will run for all query, mutation and subscription operations (including those with errors).
Logging of context creation failure can be enabled by supplying a logger to the contextCreationFailureLogger option.
logLevel: the log level to use (default:info)ignoreIntrospectionQueries: iftrue, introspection queries will not be logged (default:true)contextCreationFailureLogger: The plugin does not have access to a logger prior to context creation, so if you wish to log context creation failures, supply a logger here (it will only be called for context creation failure).contextCreationDidFail: If you wish to custom log or otherwise react to context creation failures, supply a handler for the plugincontextCreationDidFailhook (this will be called instead of logging tocontextCreationFailureLogger).shouldIgnore: an optional callback that can be used to ignore certain operations, e.g. if you have a healthcheck operation that you prefer not to be logged.includeResponseData: iftrue, the operation'sresult.datawill be included in the log output (default:false)includeMutationResponseData: iftrue, the operation'sresult.datawill be included in the log output for mutations only (default:false)adjustVariables: an optional callback that can be used to adjust the operation'svariablesbefore loggingadjustResultData: an optional callback that can be used to adjust the operation'sresult.databefore logging
const plugins: ApolloServerPlugin<GraphQLContext>[] = [
graphqlOperationLoggingPlugin<GraphQLContext, Logger>({
logLevel: 'audit',
contextCreationFailureLogger: logger,
includeMutationResponseData: true,
adjustVariables: (variables) => pruneKeys(variables, 'headers'),
}),
]Output includes:
type: the GraphQL operation type:query,mutationorsubscriptionoperationName: the optional operation namequery: the formatted operationduration: milliseconds taken to process the operation from context creation towillSendResponsehookvariables: the optional operation variables, optionally adjusted by theadjustVariablescallbackresult.errors: the operation'sGraphQLFormattedError[], if anyresult.data: the operation's data result, ifincludeResponseDataistrueorincludeMutationResponseDataistrueand the operation is a mutation, optionally adjusted by theadjustResultDatacallbackisIncrementalResponse:trueif the operation is part of an incremental delivery response (@deferor@stream)isSubsequentPayload:trueif the operation is a subsequent payload of an incremental delivery response
introspectionControlPlugin implements a standard pattern of rejecting unauthorized introspection requests in production.
- Unauthorized requests are those that do not have a
userset on the GraphQL context. - Production is determined according to
NODE_ENV === 'production'via node-common
Apollo Server v4 introduced an executeOperation function to enable operations to be run directly against the server instance, without requiring an HTTP server or network calls.
Bypassing the HTTP stack supports complete control over JWT payloads and other operation context inputs required to set up complex test scenarios.
The @makerx/graphql-apollo-server/testing module exports buildExecuteOperation, which accepts an ApolloServer instance and a context creation function and returns an executeOperation function which:
- is strongly typed to the GraphQL context
- accepts
TypedDocumentNodeoperations to provide strong operation typing - forwards any additional arguments to the supplied context creation function
The shape of the context creation function — and the JWT/user factories used to drive it — depends on your GraphQL implementation, so the examples below illustrate one common pattern using Vitest test contexts.
Note: exact shape depends on your auth implementation.
test/auth.ts
export interface BuildJwtInput {
oid: string
tid: string
sub: string
iss: string
aud: string | string[]
email: string
name: string
scopes: string[]
roles: string[]
idtyp?: string | 'app'
}
const buildJwt = ({
oid = randomUUID(),
tid = randomUUID(),
sub = randomUUID(),
iss = randomUUID(),
aud = randomUUID(),
email = faker.internet.email(),
name = faker.person.fullName(),
scopes = [],
roles = [],
...rest
}: Partial<BuildJwtInput> = {}): JwtPayload => ({
oid,
tid,
sub,
iss,
aud,
email,
name,
scp: scopes.join(' '),
roles,
...rest,
})
const buildUserJwt = (input: Partial<BuildJwtInput> = {}): JwtPayload => buildJwt({ ...input, roles: [UserRoles.User] })
const buildSystemAdminJwt = (input: Partial<BuildJwtInput> = {}): JwtPayload => buildJwt({ ...input, roles: [UserRoles.SystemAdmin] })
export const test = baseTest.extend('auth', {
buildJwt,
buildUserJwt,
buildSystemAdminJwt,
})Note: extend auth context or other context as required.
test/graphql.ts
import { test as baseTest } from './auth'
const requestInfo: RequestInfo = {
source: 'http',
protocol: 'http',
baseUrl: 'http://localhost',
host: 'localhost',
url: '/graphql',
method: 'TEST',
origin: 'vitest',
requestId: 'test',
}
const createContext = async (jwtPayload?: JwtPayload): Promise<GraphQLContext> => {
const user = await findUpdateOrCreateUser(jwtPayload, randomUUID())
const baseContext: BaseContext = { user, logger, requestInfo, started: Date.now() }
const extraContext = await augmentContext(baseContext)
return { ...baseContext, ...extraContext }
}
export const test = baseTest.extend('executeOperation', { scope: 'worker' }, async ({}, { onCleanup }) => {
const schema = createSchema()
const server = new ApolloServer<GraphQLContext>({ schema })
onCleanup(() => server.stop())
return buildExecuteOperation(server, createContext)
})The test files below use the graphql template-literal tag from GraphQL-Codegen to produce strongly typed operations.
import { describe, expect } from 'vitest'
import { graphql } from './gql'
import { test } from './graphql'
const helloQuery = graphql(`
query Hello($message: String) {
hello(message: $message)
}
`)
describe('hello query operation', () => {
test('anonymous calls fail', async ({ executeOperation }) => {
const result = await executeOperation({ query: helloQuery, variables: { message: 'world' } })
expect(result.errors?.[0]?.message).toBe('Not authenticated')
})
test('authenticated calls work', async ({ executeOperation, buildUserJwt }) => {
const result = await executeOperation({ query: helloQuery, variables: { message: 'world' } }, buildUserJwt())
expect(result.data?.hello).toBe('Hello, world!')
})
test('user name is returned', async ({ executeOperation, buildUserJwt }) => {
const result = await executeOperation({ query: helloQuery }, buildUserJwt({ name: 'Magda' }))
expect(result.data?.hello).toBe('Hello, Magda!')
})
test('user email is returned', async ({ executeOperation, buildUserJwt }) => {
const result = await executeOperation({ query: helloQuery }, buildUserJwt({ email: 'magda@magda.net' }))
expect(result.data?.hello).toBe('Hello, magda@magda.net!')
})
})import { describe, expect } from 'vitest'
import { graphql } from './gql'
import { test } from './graphql'
const importantMutation = graphql(`
mutation Important {
important
}
`)
describe('important mutation operation', () => {
test('anonymous calls fail', async ({ executeOperation }) => {
const result = await executeOperation({ query: importantMutation })
expect(result.errors?.[0]?.message).toBe('Not authorized')
})
test('non-admin calls fail', async ({ executeOperation, buildUserJwt }) => {
const result = await executeOperation({ query: importantMutation }, buildUserJwt())
expect(result.errors?.[0]?.message).toBe('Not authorized')
})
test('admin calls work', async ({ executeOperation, buildSystemAdminJwt }) => {
const result = await executeOperation({ query: importantMutation }, buildSystemAdminJwt())
expect(result.data?.important).toBe('Operation successful')
})
})This test shows how the context input JWT payload can be easily controlled when operating underneath the HTTP layer where Bearer token validation and decoding would normally be required.
import { describe, expect } from 'vitest'
import { graphql } from './gql'
import { test } from './graphql'
const meQuery = graphql(`
query Me {
me {
id
name
email
roles
}
}
`)
describe('me query operation', () => {
test('anonymous calls return null', async ({ executeOperation }) => {
const result = await executeOperation({ query: meQuery })
expect(result.data?.me).toBeNull()
})
test('returns basic user', async ({ executeOperation, buildUserJwt }) => {
const jwt = buildUserJwt()
const result = await executeOperation({ query: meQuery }, jwt)
expect(result.data?.me).toMatchObject({
id: jwt.oid,
email: jwt.email,
})
})
test('returns user roles', async ({ executeOperation, buildJwt }) => {
const jwt = buildJwt({ roles: ['Admin', 'Supervisor'] })
const result = await executeOperation({ query: meQuery }, jwt)
expect(result.data?.me).toMatchObject({
id: jwt.oid,
email: jwt.email,
roles: jwt.roles,
})
})
test('returns user name', async ({ executeOperation, buildUserJwt }) => {
const jwt = buildUserJwt({ name: 'Magda' })
const result = await executeOperation({ query: meQuery }, jwt)
expect(result.data?.me).toMatchObject({
id: jwt.oid,
email: jwt.email,
name: jwt.name,
})
})
})