Foz*_*afi 3 apollo graphql apollo-server
我正在尝试使用 apollo 服务器实现自定义指令。我从官方网站上拿了例子。
我的查询如下:
directive @upper on FIELD_DEFINITION
type Query {
hello: String @upper
}
Run Code Online (Sandbox Code Playgroud)
我的解析器如下所示:
Query:{
async hello(){
return "hello world";
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的自定义指令的阿波罗服务器配置:
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()
});
Run Code Online (Sandbox Code Playgroud)
我总是得到的输出:
{
"data": {
"hello": "hello world"
}
}
Run Code Online (Sandbox Code Playgroud)
为什么自定义指令未激活?为什么输出不是大写?
如果正在为您构建架构,您将传递schemaDirectivestoApolloServer的构造函数ApolloServer——也就是说,如果您还传入了resolversand typeDefs。如果你传入一个现有的模式,它已经构建好了,ApolloServer 不会应用这些指令。如果您正在使用makeExecutableSchema,您可以将您的传递schemaDirectives给那个。也可以像这样手动访问所有指令:
SchemaDirectiveVisitor.visitSchemaDirectives(schema, schemaDirectives)
Run Code Online (Sandbox Code Playgroud)
这是使指令与某些库(如graphql-modules.
| 归档时间: |
|
| 查看次数: |
981 次 |
| 最近记录: |