Skip to content

Commit

Permalink
Factor out runQuery's use of logFunction into an extension (#1128)
Browse files Browse the repository at this point in the history
This requires a slightly newer graphql-extensions beta which has more arguments
to requestDidStart.

Also make it ok to not pass logFunction to formatApolloErrors, and make sure
custom fieldResolvers continue to work with extensions (by upgrading the
dependency and fixing a logic bug).

The custom fieldResolvers fix means that we now unconditionally put the
extension stack on the GraphQL context, which means that the context can no
longer be (say) a string.  I changed a test that expected string contexts to
work. You couldn't use a string for a context when using extensions before, so
this isn't that big of a change.
  • Loading branch information
glasser authored Jun 2, 2018
1 parent 836616b commit 5c65742
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 60 deletions.
2 changes: 1 addition & 1 deletion packages/apollo-server-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"apollo-cache-control": "^0.1.1",
"apollo-engine-reporting": "0.0.0-beta.8",
"apollo-tracing": "^0.2.0-beta.0",
"graphql-extensions": "0.1.0-beta.7",
"graphql-extensions": "0.1.0-beta.12",
"graphql-subscriptions": "^0.5.8",
"graphql-tools": "^3.0.2",
"node-fetch": "^2.1.2",
Expand Down
13 changes: 7 additions & 6 deletions packages/apollo-server-core/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,12 +245,13 @@ export function formatApolloErrors(
try {
return formatter(error);
} catch (err) {
logFunction({
action: LogAction.cleanup,
step: LogStep.status,
data: err,
key: 'error',
});
logFunction &&
logFunction({
action: LogAction.cleanup,
step: LogStep.status,
data: err,
key: 'error',
});

if (debug) {
return enrichError(err, debug);
Expand Down
81 changes: 81 additions & 0 deletions packages/apollo-server-core/src/logging.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { GraphQLExtension, GraphQLResponse } from 'graphql-extensions';
import { print, DocumentNode } from 'graphql';

export enum LogAction {
request,
parse,
Expand All @@ -23,3 +26,81 @@ export interface LogMessage {
export interface LogFunction {
(message: LogMessage);
}

// A GraphQLExtension that implements the existing logFunction interface. Note
// that now that custom extensions are supported, you may just want to do your
// logging as a GraphQLExtension rather than write a LogFunction.

export class LogFunctionExtension<TContext = any>
implements GraphQLExtension<TContext> {
private logFunction: LogFunction;
public constructor(logFunction: LogFunction) {
this.logFunction = logFunction;
}

public requestDidStart(options: {
request: Request;
queryString?: string;
parsedQuery?: DocumentNode;
operationName?: string;
variables?: { [key: string]: any };
}) {
this.logFunction({ action: LogAction.request, step: LogStep.start });
const loggedQuery = options.queryString || print(options.parsedQuery);
this.logFunction({
action: LogAction.request,
step: LogStep.status,
key: 'query',
data: loggedQuery,
});
this.logFunction({
action: LogAction.request,
step: LogStep.status,
key: 'variables',
data: options.variables,
});
this.logFunction({
action: LogAction.request,
step: LogStep.status,
key: 'operationName',
data: options.operationName,
});

return (...errors: Array<Error>) => {
// If there are no errors, we log in willSendResponse instead.
if (errors.length) {
this.logFunction({ action: LogAction.request, step: LogStep.end });
}
};
}

public parsingDidStart() {
this.logFunction({ action: LogAction.parse, step: LogStep.start });
return () => {
this.logFunction({ action: LogAction.parse, step: LogStep.end });
};
}

public validationDidStart() {
this.logFunction({ action: LogAction.validation, step: LogStep.start });
return () => {
this.logFunction({ action: LogAction.validation, step: LogStep.end });
};
}

public executionDidStart() {
this.logFunction({ action: LogAction.execute, step: LogStep.start });
return () => {
this.logFunction({ action: LogAction.execute, step: LogStep.end });
};
}

public willSendResponse(o: { graphqlResponse: GraphQLResponse }) {
this.logFunction({
action: LogAction.request,
step: LogStep.end,
key: 'response',
data: o.graphqlResponse,
});
}
}
8 changes: 4 additions & 4 deletions packages/apollo-server-core/src/runQuery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const queryType = new GraphQLObjectType({
testContextValue: {
type: GraphQLString,
resolve(_root, _args, context) {
return context + ' works';
return context.s + ' works';
},
},
testArgumentValue: {
Expand Down Expand Up @@ -193,7 +193,7 @@ describe('runQuery', () => {
return runQuery({
schema,
queryString: query,
context: 'it still',
context: { s: 'it still' },
request: new MockReq(),
}).then(res => {
expect(res.data).to.deep.equal(expected);
Expand All @@ -206,9 +206,9 @@ describe('runQuery', () => {
return runQuery({
schema,
queryString: query,
context: 'it still',
context: { s: 'it still' },
formatResponse: (response, { context }) => {
response['extensions'] = context;
response['extensions'] = context.s;
return response;
},
request: new MockReq(),
Expand Down
69 changes: 20 additions & 49 deletions packages/apollo-server-core/src/runQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
ExecutionResult,
DocumentNode,
parse,
print,
validate,
execute,
ExecutionArgs,
Expand All @@ -29,7 +28,7 @@ import {
SyntaxError,
} from './errors';

import { LogStep, LogAction, LogFunction } from './logging';
import { LogFunction, LogFunctionExtension } from './logging';

export interface GraphQLResponse {
data?: object;
Expand Down Expand Up @@ -86,20 +85,14 @@ function doRunQuery(options: QueryOptions): Promise<GraphQLResponse> {
throw new Error('Must supply one of queryString and parsedQuery');
}

const logFunction =
options.logFunction ||
function() {
return null;
};
const debugDefault =
process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test';
const debug = options.debug !== undefined ? options.debug : debugDefault;

logFunction({ action: LogAction.request, step: LogStep.start });

const context = options.context || {};

// If custom extension factories were provided, create per-request extension objects.
// If custom extension factories were provided, create per-request extension
// objects.
const extensions = options.extensions ? options.extensions.map(f => f()) : [];

// Legacy hard-coded extension factories. The ApolloServer class doesn't use
Expand All @@ -112,54 +105,44 @@ function doRunQuery(options: QueryOptions): Promise<GraphQLResponse> {
} else if (options.cacheControl) {
extensions.push(new CacheControlExtension(options.cacheControl));
}
if (options.logFunction) {
extensions.push(new LogFunctionExtension(options.logFunction));
}

const extensionStack = new GraphQLExtensionStack(extensions);

// We unconditionally create an extensionStack (so that we don't have to
// litter the rest of this function with `if (extensionStack)`, but we don't
// instrument the schema unless there actually are extensions.
// We unconditionally create an extensionStack, even if there are no
// extensions (so that we don't have to litter the rest of this function with
// `if (extensionStack)`, but we don't instrument the schema unless there
// actually are extensions. We do unconditionally put the stack on the
// context, because if some other call had extensions and the schema is
// already instrumented, that's the only way to get a custom fieldResolver to
// work.
if (extensions.length > 0) {
context._extensionStack = extensionStack;
enableGraphQLExtensions(options.schema);
}
context._extensionStack = extensionStack;

const requestDidEnd = extensionStack.requestDidStart({
// Since the Request interfacess are not the same between node-fetch and
// typescript's lib dom, we should limit the fields that need to be passed
// into requestDidStart to only the ones we need, currently just the
// headers, method, and url
request: options.request as any,
queryString: options.queryString,
parsedQuery: options.parsedQuery,
operationName: options.operationName,
variables: options.variables,
});
return Promise.resolve()
.then(() => {
const loggedQuery = options.queryString || print(options.parsedQuery);
logFunction({
action: LogAction.request,
step: LogStep.status,
key: 'query',
data: loggedQuery,
});
logFunction({
action: LogAction.request,
step: LogStep.status,
key: 'variables',
data: options.variables,
});
logFunction({
action: LogAction.request,
step: LogStep.status,
key: 'operationName',
data: options.operationName,
});

// Parse the document.
let documentAST: DocumentNode;
if (options.parsedQuery) {
documentAST = options.parsedQuery;
} else if (!options.queryString) {
throw new Error('Must supply one of queryString and parsedQuery');
} else {
logFunction({ action: LogAction.parse, step: LogStep.start });
const parsingDidEnd = extensionStack.parsingDidStart({
queryString: options.queryString,
});
Expand All @@ -180,7 +163,6 @@ function doRunQuery(options: QueryOptions): Promise<GraphQLResponse> {
);
} finally {
parsingDidEnd(...(graphqlParseErrors || []));
logFunction({ action: LogAction.parse, step: LogStep.end });
if (graphqlParseErrors) {
return Promise.resolve({ errors: graphqlParseErrors });
}
Expand All @@ -200,7 +182,6 @@ function doRunQuery(options: QueryOptions): Promise<GraphQLResponse> {
if (options.validationRules) {
rules = rules.concat(options.validationRules);
}
logFunction({ action: LogAction.validation, step: LogStep.start });
const validationDidEnd = extensionStack.validationDidStart();
let validationErrors;
try {
Expand All @@ -217,14 +198,13 @@ function doRunQuery(options: QueryOptions): Promise<GraphQLResponse> {
),
{
formatter: options.formatError,
logFunction,
logFunction: options.logFunction,
debug,
},
);
}
} finally {
validationDidEnd(...(validationErrors || []));
logFunction({ action: LogAction.validation, step: LogStep.end });

if (validationErrors && validationErrors.length) {
return Promise.resolve({
Expand All @@ -243,7 +223,6 @@ function doRunQuery(options: QueryOptions): Promise<GraphQLResponse> {
operationName: options.operationName,
fieldResolver: options.fieldResolver,
};
logFunction({ action: LogAction.execute, step: LogStep.start });
const executionDidEnd = extensionStack.executionDidStart({
executionArgs,
});
Expand Down Expand Up @@ -271,13 +250,12 @@ function doRunQuery(options: QueryOptions): Promise<GraphQLResponse> {
if (result.errors) {
response.errors = formatApolloErrors([...result.errors], {
formatter: options.formatError,
logFunction,
logFunction: options.logFunction,
debug,
});
}

executionDidEnd(...result.errors);
logFunction({ action: LogAction.execute, step: LogStep.end });

const formattedExtensions = extensionStack.format();
if (Object.keys(formattedExtensions).length > 0) {
Expand All @@ -296,18 +274,11 @@ function doRunQuery(options: QueryOptions): Promise<GraphQLResponse> {
// we're not returning a GraphQL response so we don't call
// willSendResponse.
requestDidEnd(err);
logFunction({ action: LogAction.request, step: LogStep.end });
throw err;
})
.then(graphqlResponse => {
extensionStack.willSendResponse({ graphqlResponse });
requestDidEnd();
logFunction({
action: LogAction.request,
step: LogStep.end,
key: 'response',
data: graphqlResponse,
});
return graphqlResponse;
});
}

0 comments on commit 5c65742

Please sign in to comment.