为什么Apollo服务器自定义指令不起作用?

时间:2020-04-21 22:21:42

标签: graphql apollo apollo-server

我正在尝试用apollo服务器实现自定义指令。我以官方网站为例。

我的查询如下:

directive @upper on FIELD_DEFINITION

type Query {
  hello: String @upper
}

我的解析器如下:

Query:{
        async hello(){
            return "hello world";
        }
    }

这是我的自定义指令的apollo服务器配置:

const { ApolloServer, SchemaDirectiveVisitor } = require('apollo-server-express');
const { defaultFieldResolver } = require("graphql");

class UpperCaseDirective extends SchemaDirectiveVisitor {
    visitFieldDefinition(field) {
      const { resolve = defaultFieldResolver } = field;
      field.resolve = async function (...args) {
        const result = await resolve.apply(this, args);
        if (typeof result === "string") {
          return result.toUpperCase();
        }
        return result;
      };
    }
  }

const server = new ApolloServer({
    schema,
    schemaDirectives: {
        upper: UpperCaseDirective
    },
    introspection: true,
    playground: true,
    cors: cors()

});

我总是得到的输出:

{
  "data": {
    "hello": "hello world"
  }
} 

为什么未激活自定义指令?为什么输出的内容不是大写?

1 个答案:

答案 0 :(得分:3)

如果schemaDirectives正在为您构建架构,也就是说,如果您还传递了ApolloServer和{ {1}}。如果要传递现有模式,则它已经构建,并且ApolloServer不会应用指令。如果您使用的是ApolloServer,则可以将resolvers传递给它。也可以像这样手动访问所有指令:

typeDefs

这是使指令与某些库(例如makeExecutableSchema)一起使用的唯一方法。