[英]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.