GraphQL(Apollo):您可以在resolve函数中访问指令吗?

时间:2018-12-30 02:00:42

标签: javascript graphql apollo graphql-js apollo-server

我想将每个字段都设为私有,除非用指令另外指出。是否可以在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 });

1 个答案:

答案 0 :(得分:1)

虽然directives数组中FieldNode对象上有一个fieldNodes属性,但据我所知,该属性未填充适用于该特定字段的指令。 / p>

指令并不是真的要用作可在解析程序中引用的内容(模式级别或其他)的标志。您可以考虑在指令的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,
  },
})