gpt4 book ai didi

javascript - GraphQL( Apollo ): Can you access directives within resolve function?

转载 作者:行者123 更新时间:2023-11-29 18:45:54 25 4
gpt4 key购买 nike

我想将每个字段设为私有(private),除非另有指示。是否可以在解析函数中获取此信息?

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 属性,但据我所知,它没有填充适用于该特定领域的指令。

指令并不是真的要用作可以在解析器(架构级别或其他方式)中引用的内容的标志。您可以考虑将逻辑移到指令的 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,
},
})

关于javascript - GraphQL( Apollo ): Can you access directives within resolve function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53974759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com