-
Notifications
You must be signed in to change notification settings - Fork 2k
/
logging.ts
106 lines (94 loc) · 2.67 KB
/
logging.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { GraphQLExtension, GraphQLResponse } from 'graphql-extensions';
import { print, DocumentNode } from 'graphql';
export enum LogAction {
request,
parse,
validation,
execute,
setup,
cleanup,
}
export enum LogStep {
start,
end,
status,
}
export interface LogMessage {
action: LogAction;
step: LogStep;
key?: string;
data?: any;
}
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,
});
}
}