[英]GraphQL (Apollo): Can you access directives within resolve function?
I'd like to make every field private, unless otherwise notated with a directive. 我想将每个字段都设为私有,除非另有指示。 Is it possible to get this information within a 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 });
While there is a directives
property on FieldNode
object in the fieldNodes
array, as far as I'm aware it's not populated with the directives that apply to that specific field. 虽然在
fieldNodes
数组的FieldNode
对象上有一个directives
属性, FieldNode
据我所知,它没有填充适用于该特定字段的伪指令。
Directives aren't really meant to be used as a flag for something that can be referenced in a resolver (schema level or otherwise). 指令并不是真的要用作可在解析程序中引用的内容(架构级别或其他)的标志。 You may consider moving your logic inside the directive's
visitFieldDefinition
function: 您可以考虑在指令的
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.