Я пытаюсь прикрепить результаты validationRule
к response
или context
в Apollo Server.
Исходным фоном является то, что я добавляю правило проверки сложности запроса (используя this graphql-validation-Трудность lib), но перед добавлением ошибки проверки я хотел бы отследить среднюю сложность обычного пользовательские запросы. Я пишу журналы с расширением , чтобы у меня был доступ к context
и response
, поэтому получение результатов проверки на любом из них (независимо от того, прошла проверка или нет) будь идеальным.
Похоже, что плагины для проверки имеют доступ к чему-то, что называется validationContext
(здесь источник этого из библиотеки graphql.js lib ), но это не то же самое, что запрос context
, поэтому у меня возникли проблемы с выводом результатов проверки.
Вот тестовый пример с несколькими комментариями о том, что я пытаюсь сделать:
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}`);
});
и package.json
для установки из:
{
"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"
}
}
(чтобы запустить этот пример, создайте новую папку, запишите второй блок в package.json
, запишите первый блок в index.js
, запустите npm install
, затем npm run start
)
Кто-нибудь знает, как прикрепить результаты validationRule
к context
или response
?