【问题标题】:Why apollo server custom directive not working?为什么阿波罗服务器自定义指令不起作用?
【发布时间】:2020-08-04 19:57:22
【问题描述】:

我正在尝试使用 apollo 服务器实现自定义指令。我是从官网拿的例子。

我的查询如下:

directive @upper on FIELD_DEFINITION

type Query {
  hello: String @upper
}

我的解析器如下:

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

这是我的自定义指令的阿波罗服务器配置:

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"
  }
} 

为什么自定义指令没有被激活?为什么输出不是大写的?

【问题讨论】:

    标签: graphql apollo apollo-server


    【解决方案1】:

    如果ApolloServer 正在为您构建您的模式,您将把schemaDirectives 传递给ApolloServer 的构造函数——也就是说,如果您还传递了resolverstypeDefs。如果你传入一个现有的模式,它已经构建好了,ApolloServer 不会应用这些指令。如果您使用的是makeExecutableSchema,您可以将您的schemaDirectives 传递给它。也可以像这样手动访问所有指令:

    SchemaDirectiveVisitor.visitSchemaDirectives(schema, schemaDirectives)
    

    这是让指令与某些库一起使用的唯一方法,例如 graphql-modules

    【讨论】:

    • 非常感谢,当我传入'makeExecutableSchema'时它正在工作
    猜你喜欢
    • 1970-01-01
    • 2018-04-26
    • 2021-09-09
    • 2019-02-08
    • 2020-10-18
    • 2017-12-11
    • 2020-12-26
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多