将验证结果附加到Apollo Server中的“上下文”或“响应”

时间:2019-01-20 00:36:22

标签: javascript validation graphql apollo-server

我正在尝试将validationRule的结果附加到Apollo Server中的responsecontext上。

背景是我要添加查询复杂度验证规则(使用this graphql-validation-complexity lib),但是在添加验证错误之前,我想跟踪普通用户查询的平均复杂度。我正在使用extension编写日志,这样我就可以访问contextresponse,因此将验证结果转移到其中一个(无论是否通过验证) )将是理想的选择。

验证插件似乎可以访问名为validationContext(这里为the source of that from the 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的结果附加到contextresponse上吗?

0 个答案:

没有答案