[英]GraphQL (Apollo): Can you access directives within resolve function?
我想将每个字段都设为私有,除非另有指示。 是否有可能在resolve函数中获取此信息?
const typeDefs = gql`
directive @public on FIELD_DEFINITION
type Query {
viewer: User @public
secret: String
}
type User {
id: ID!
}
`
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
addSchemaLevelResolveFunction(schema, (parent, args, params, info) => {
// Not possible
if (info.fieldName.directive === 'public') {
return parent;
}
throw new Error('Authentication required...');
});
const server = new ApolloServer({ schema });
虽然在fieldNodes
数组的FieldNode
对象上有一个directives
属性, FieldNode
据我所知,它没有填充适用于该特定字段的伪指令。
指令并不是真的要用作可在解析程序中引用的内容(架构级别或其他)的标志。 您可以考虑在指令的visitFieldDefinition
函数中移动逻辑:
const { defaultFieldResolver } = require('graphql')
const { SchemaDirectiveVisitor } = require('graphql-tools')
class PublicDirective extends SchemaDirectiveVisitor {
visitFieldDefinition(field) {
const { resolve = defaultFieldResolver } = field
field.resolve = async function (source, args, context, info) {
if (someCondition) {
throw new SomeError()
}
return resolve.apply(this, [source, args, context, info])
}
}
}
const schema = makeExecutableSchema({
typeDefs,
resolvers,
schemaResolvers: {
public: PublicDirective,
},
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.