gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:59:39 24 4
gpt4 key购买 nike

我正在尝试使用 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"
}
}

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

最佳答案

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

SchemaDirectiveVisitor.visitSchemaDirectives(schema, schemaDirectives)

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

关于graphql - 为什么 Apollo 服务器自定义指令不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61354242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com