I'm trying to attach the results of a validationRule to either the response or context in Apollo Server.
The background is that I'm adding a query complexity validation rule (using this graphql-validation-complexity lib), but before adding a validation error I'd like to track the average complexity of normal user queries. I'm writing logs with an extension so that I have access to the context and response, so getting the results of the validation onto either of those (regardless of the validation passing or not) would be ideal.
Validation plugins appear to have access to something called the validationContext (here's the source of that from the graphql.js lib), but that isn't the same as the request context, so I'm having trouble bubbling the validation results up.
Here's a test case, with a few comments about what I'm trying to do:
const { ApolloServer, gql } = require('apollo-server');
const { createComplexityLimitRule } = require('graphql-validation-complexity');
const { GraphQLExtension } = require('graphql-extensions');
// an example of using an extension for logging
class Logger extends GraphQLExtension {
willSendResponse(o) {
const { context, graphqlResponse } = o;
console.log(`This is where I'm doing logging, and would like to access the query cost`);
}
}
const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
},
];
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
const resolvers = {
Query: {
books: () => books,
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
extensions: [() => new Logger()],
validationRules: [
createComplexityLimitRule(1000, {
onCost: (cost, validationContext) => {
// how can I get this onto `context` or `request`?
console.log(`query cost: ${cost}`);
},
}),
],
});
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
And a package.json to install from:
{
"name": "apollo-question",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"apollo-server": "2.3.1",
"graphql": "14.1.1",
"graphql-extensions": "^0.4.1",
"graphql-validation-complexity": "^0.2.4"
}
}
(to run this example, make a new folder, write the second block to package.json, write the first block to index.js, run npm install, then npm run start)
Does anyone know how to attach the results of a validationRule to the context or response?