graphql - 为什么阿波罗服务器自定义指令不起作用?
问题描述
我正在尝试使用 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"
}
}
为什么自定义指令未激活?为什么输出不是大写的?
解决方案
如果正在为您构建模式,您将传递schemaDirectives
给ApolloServer
's 构造函数ApolloServer
- 也就是说,如果您还传入resolvers
and typeDefs
。如果你传入一个现有的模式,它已经构建好了,ApolloServer 不会应用这些指令。如果您正在使用makeExecutableSchema
,则可以将您的传递schemaDirectives
给它。也可以像这样手动访问所有指令:
SchemaDirectiveVisitor.visitSchemaDirectives(schema, schemaDirectives)
这是让指令与某些库一起工作的唯一方法,例如graphql-modules
.
推荐阅读
- ios - 在 Swift 语言和 Realm 数据库中声明日期对象时,是否需要格式化日期?
- python - 使用 Kosaraju 算法的图中强连通分量 (SCC) 的大小(边数)
- sql - 当发生变化时如何跟踪数据库中的变化?
- javascript - 如何显示功能组件列表
- google-cloud-platform - 在 stackdriver 上监控 VM 进程
- javascript - JS:Facebook 登录:如何从不同的页面调用 FB.logout()?
- azure - 为什么不能通过 Azure 的 API 获得数据
- python - 本地化:django-admin compilemessages skip venv
- gradle - 使用 Kotlin 实现插件时如何为 Gradle 扩展任务?
- python - json文件中布尔数据类型的反序列化在python中不起作用